<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
        
    @hotelSettings
    <title>Inventory Management - {{ hotelName() }}</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <style>
        :root {
            --primary-green: #1a936f;
            --secondary-green: #88d498;
            --light-green: #c6dabf;
            --dark-green: #114b5f;
            --accent: #f3e9d2;
            --purple: #6f42c1;
            --orange: #fd7e14;
            --teal: #20c997;
        }
        
        body {
            background: #f4f7fb;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            color: #1f2937;
        }
        
        .navbar {
            background: linear-gradient(90deg, var(--dark-green) 0%, var(--primary-green) 100%);
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        
        .main-content {
            max-width: 1440px;
            margin: 70px auto 0;
            padding: 20px 24px 32px;
        }
        
        .dashboard-card {
            border-radius: 12px;
            transition: transform 0.3s, box-shadow 0.3s;
            border: none;
            box-shadow: 0 6px 18px rgba(17, 75, 95, 0.08);
        }
        
        .dashboard-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 24px rgba(17, 75, 95, 0.14);
        }
        
        .card-header {
            background: linear-gradient(90deg, var(--primary-green) 0%, var(--secondary-green) 100%);
            color: white;
            border-radius: 12px 12px 0 0 !important;
            padding: 14px 20px;
        }
        
        .bg-primary { background-color: var(--primary-green) !important; }
        .bg-purple { background-color: var(--purple) !important; }
        .bg-orange { background-color: var(--orange) !important; }
        .bg-teal { background-color: var(--teal) !important; }
        
        .text-primary { color: var(--primary-green) !important; }
        .text-purple { color: var(--purple) !important; }
        .text-orange { color: var(--orange) !important; }
        .text-teal { color: var(--teal) !important; }
        
        .btn-primary {
            background-color: var(--primary-green);
            border-color: var(--primary-green);
            border-radius: 8px;
            padding: 10px 24px;
            font-weight: 500;
        }
        
        .btn-primary:hover {
            background-color: var(--dark-green);
            border-color: var(--dark-green);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(17, 75, 95, 0.3);
        }
        
        .btn-purple {
            background-color: var(--purple);
            border-color: var(--purple);
            color: white;
        }
        
        .btn-orange {
            background-color: var(--orange);
            border-color: var(--orange);
            color: white;
        }
        
        .btn-teal {
            background-color: var(--teal);
            border-color: var(--teal);
            color: white;
        }
        
        .inventory-status-good {
            border-left: 4px solid var(--primary-green);
            background: linear-gradient(90deg, #f8fff8 0%, #f0f8f0 100%);
        }
        
        .inventory-status-warning {
            border-left: 4px solid var(--orange);
            background: linear-gradient(90deg, #fffbf0 0%, #fef7e0 100%);
        }
        
        .inventory-status-danger {
            border-left: 4px solid #dc3545;
            background: linear-gradient(90deg, #fef0f0 0%, #fde8e8 100%);
        }
        
        .table th {
            background: linear-gradient(90deg, #114b5f 0%, #1a936f 100%);
            color: #ffffff !important;
            font-weight: 600;
            border: none;
            position: sticky;
            top: 0;
            z-index: 10;
            white-space: nowrap;
            padding: 12px 10px;
        }
        
        .table td {
            border-color: #e9ecef;
            vertical-align: middle;
            padding: 10px;
        }

        /* Keep action dropdown visible above table wrappers */
        .table-responsive {
            overflow-x: auto;
            overflow-y: visible;
        }

        .item-action-buttons .dropdown-menu {
            z-index: 1200;
        }
        
        .welcome-banner {
            background: linear-gradient(135deg, var(--dark-green) 0%, var(--primary-green) 100%);
            border-radius: 12px;
            color: white;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 4px 15px rgba(17, 75, 95, 0.2);
        }

        /* Action Bar */
        .action-bar {
            background: white;
            border-radius: 12px;
            padding: 18px 20px;
            margin-bottom: 25px;
            border: 1px solid #e9ecef;
            box-shadow: 0 4px 16px rgba(15, 23, 42, 0.06);
            position: sticky;
            top: 72px;
            z-index: 20;
        }

        .action-bar-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .action-bar-title {
            font-size: 1.3rem;
            font-weight: 600;
            color: var(--dark-green);
            margin: 0;
        }

        .action-bar-actions {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            justify-content: flex-end;
        }

        .action-btn {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 10px 20px;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s ease;
            text-decoration: none;
            border: none;
            cursor: pointer;
        }

        .action-btn-primary {
            background: linear-gradient(135deg, var(--primary-green) 0%, var(--secondary-green) 100%);
            color: white;
            box-shadow: 0 4px 12px rgba(26, 147, 111, 0.3);
        }

        .action-btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(26, 147, 111, 0.4);
            color: white;
        }

        .action-btn-secondary {
            background: white;
            color: var(--primary-green);
            border: 2px solid var(--primary-green);
        }

        .action-btn-secondary:hover {
            background: var(--primary-green);
            color: white;
            transform: translateY(-2px);
        }

        .action-btn-outline {
            background: white;
            color: var(--dark-green);
            border: 2px solid #dee2e6;
        }

        .action-btn-outline:hover {
            background: #f8f9fa;
            border-color: var(--primary-green);
            color: var(--primary-green);
            transform: translateY(-2px);
        }

        .quick-stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            border-radius: 12px;
            overflow: hidden;
            position: relative;
            border: none;
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 5px;
            background: linear-gradient(90deg, var(--primary-green) 0%, var(--secondary-green) 100%);
        }

        .stat-card.warning::before {
            background: linear-gradient(90deg, var(--orange) 0%, #ffb347 100%);
        }

        .stat-card.danger::before {
            background: linear-gradient(90deg, #dc3545 0%, #ff6b6b 100%);
        }

        .stat-card.purple::before {
            background: linear-gradient(90deg, var(--purple) 0%, #9c88ff 100%);
        }

        .stat-card.teal::before {
            background: linear-gradient(90deg, var(--teal) 0%, #64dfdf 100%);
        }

        .stat-icon {
            width: 50px;
            height: 50px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
        }

        .progress-thin {
            height: 6px;
            border-radius: 3px;
        }

        .filter-card {
            background: #ffffff;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            border: 1px solid #dee2e6;
            box-shadow: 0 4px 14px rgba(15, 23, 42, 0.05);
        }

        .stock-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 8px;
        }
        
        .stock-good { background-color: var(--primary-green); }
        .stock-warning { background-color: var(--orange); }
        .stock-danger { background-color: #dc3545; }

        .status-badge {
            padding: 6px 14px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
        }

        .quick-actions {
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 1000;
        }

        .quick-action-btn {
            width: 56px;
            height: 56px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
            transition: all 0.3s;
        }

        .quick-action-btn:hover {
            transform: scale(1.1);
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
        }

        .department-badge {
            background-color: #e3f2fd;
            color: #1565c0;
            padding: 4px 10px;
            border-radius: 12px;
            font-size: 0.8rem;
            font-weight: 500;
        }

        .transaction-badge {
            padding: 4px 10px;
            border-radius: 12px;
            font-size: 0.8rem;
            font-weight: 500;
        }

        .transaction-in { background-color: #d4edda; color: #155724; }
        .transaction-out { background-color: #f8d7da; color: #721c24; }
        .transaction-adjustment { background-color: #fff3cd; color: #856404; }

        .item-action-buttons {
            display: flex;
            gap: 0.5rem;
            flex-wrap: wrap;
            align-items: center;
        }
        .item-action-buttons .btn,
        .item-action-buttons .dropdown-toggle {
            min-width: 34px;
        }

        .modal-xl-custom {
            max-width: 1100px;
        }

        .nav-tabs .nav-link {
            color: var(--dark-green);
            font-weight: 500;
            border: none;
            padding: 12px 24px;
        }

        .nav-tabs .nav-link.active {
            color: var(--primary-green);
            border-bottom: 3px solid var(--primary-green);
            background: transparent;
        }

        @media (max-width: 768px) {
            .main-content {
                margin-top: 64px;
                padding: 12px;
            }
            
            .action-bar-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
            }

            .action-bar-actions {
                width: 100%;
                justify-content: space-between;
            }

            .quick-stats-grid {
                grid-template-columns: 1fr;
            }

            .quick-actions {
                bottom: 14px;
                right: 14px;
            }

            .action-bar {
                position: static;
            }

            .welcome-banner {
                padding: 16px;
            }
        }

        .hover-shadow {
            transition: box-shadow 0.3s ease;
        }

        .hover-shadow:hover {
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }

        .cursor-pointer {
            cursor: pointer;
        }

        .text-underline-hover:hover {
            text-decoration: underline;
        }

        .fade-in {
            animation: fadeIn 0.5s ease-in;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .pulse {
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0% { box-shadow: 0 0 0 0 rgba(26, 147, 111, 0.7); }
            70% { box-shadow: 0 0 0 10px rgba(26, 147, 111, 0); }
            100% { box-shadow: 0 0 0 0 rgba(26, 147, 111, 0); }
        }

        .scroll-to-top {
            position: fixed;
            bottom: 80px;
            right: 30px;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--primary-green);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            z-index: 1000;
            opacity: 0;
            transition: opacity 0.3s;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
        }

        .scroll-to-top.show {
            opacity: 1;
        }

        .category-badge {
            background: linear-gradient(135deg, var(--light-green) 0%, #d4e6d1 100%);
            color: var(--dark-green);
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 0.8rem;
            font-weight: 500;
            border: 1px solid var(--secondary-green);
        }

        /* PDF Export Styles */
        .pdf-export-options {
            display: none;
        }

        .pdf-export-modal .modal-content {
            border-radius: 15px;
        }

        .pdf-export-modal .modal-header {
            background: linear-gradient(135deg, var(--dark-green) 0%, var(--primary-green) 100%);
            color: white;
            border-radius: 15px 15px 0 0;
        }

        .pdf-option-card {
            border: 2px solid #e9ecef;
            border-radius: 10px;
            transition: all 0.3s;
            cursor: pointer;
        }

        .pdf-option-card:hover {
            border-color: var(--primary-green);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }

        .pdf-option-card.selected {
            border-color: var(--primary-green);
            background-color: rgba(26, 147, 111, 0.05);
        }

        .pdf-option-icon {
            width: 60px;
            height: 60px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.8rem;
            margin-bottom: 15px;
        }

        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.9);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 9999;
            display: none;
        }

        .loading-spinner-pdf {
            width: 50px;
            height: 50px;
            border: 5px solid #f3f3f3;
            border-top: 5px solid var(--primary-green);
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* Category dropdown improvements */
        .category-select-wrapper {
            position: relative;
        }

        .category-select-wrapper .loading-categories {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            display: none;
        }

        .category-select-wrapper.loading .loading-categories {
            display: block;
        }

        .category-option-group {
            font-weight: bold;
            color: var(--dark-green);
            background-color: #f8f9fa;
        }

        .category-option {
            padding-left: 20px;
            font-weight: normal;
        }
    </style>
</head>
<body>
    <!-- Quick Actions Floating Buttons -->
    <div class="quick-actions">
        <button class="quick-action-btn btn btn-primary mb-2" data-bs-toggle="modal" data-bs-target="#addItemModal" title="Add New Item">
            <i class="fas fa-plus"></i>
        </button>
        <button class="quick-action-btn btn btn-orange mb-2" data-bs-toggle="modal" data-bs-target="#issueStockModal" title="Issue Stock">
            <i class="fas fa-hand-holding"></i>
        </button>
        <button class="quick-action-btn btn btn-teal mb-2" data-bs-toggle="modal" data-bs-target="#quickAdjustModal" title="Quick Stock Adjustment">
            <i class="fas fa-exchange-alt"></i>
        </button>
        <a href="{{ route('purchase-orders.index') }}" class="quick-action-btn btn btn-purple" title="Purchase Orders">
            <i class="fas fa-clipboard-list"></i>
        </a>
    </div>

    <!-- PDF Loading Overlay -->
    <div class="loading-overlay" id="pdfLoadingOverlay">
        <div class="loading-spinner-pdf"></div>
        <h4 class="mt-3">Generating PDF Report...</h4>
        <p class="text-muted">Please wait while we prepare your document</p>
        <div class="progress mt-3" style="width: 300px;">
            <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 100%"></div>
        </div>
    </div>

    <!-- Scroll to Top -->
    <div class="scroll-to-top" id="scrollToTop">
        <i class="fas fa-chevron-up"></i>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <!-- Welcome Banner -->
        <div class="welcome-banner">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h2><i class="fas fa-warehouse me-2"></i>Inventory Management System</h2>
                    <p class="mb-0">Track, manage, and optimize your hotel inventory in real-time</p>
                </div>
                <div class="col-md-4 text-md-end">
                    <a href="{{ route('dashboard') }}" class="btn btn-sm btn-outline-light mb-2">
                        <i class="fas fa-arrow-left me-1"></i> Back to Dashboard
                    </a>
                    <p class="mb-0"><i class="fas fa-calendar me-2"></i>{{ date('l, F j, Y') }}</p>
                    <p class="mb-0"><i class="fas fa-boxes me-2"></i>{{ $totalItems }} Total Items</p>
                </div>
            </div>
        </div>

        <!-- Quick Stats -->
        <div class="quick-stats-grid">
            <div class="card dashboard-card stat-card">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col">
                            <div class="text-muted text-uppercase small mb-1">Total Inventory Value</div>
                            <div class="h4 mb-0 fw-bold">UGX {{ number_format($totalValue, 0) }}</div>
                            <div class="mt-2">
                                <span class="text-success small">
                                  <i class="fas fa-chart-line me-1"></i>{{ $valueChange ?? '0.0' }}% from last month
                                </span>
                            </div>
                        </div>
                        <div class="col-auto">
                            <div class="stat-icon bg-primary bg-opacity-10 text-primary">
                                <i class="fas fa-money-bill-wave"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card dashboard-card stat-card teal">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col">
                            <div class="text-muted text-uppercase small mb-1">Active Items</div>
                            <div class="h4 mb-0 fw-bold">{{ $totalItems }}</div>
                            <div class="progress progress-thin mt-2">
                                <div class="progress-bar bg-teal" style="width: {{ ($activeItems / max($totalItems, 1)) * 100 }}%"></div>
                            </div>
                            <div class="small mt-1">{{ $activeItems }} active, {{ $inactiveItems }} inactive</div>
                        </div>
                        <div class="col-auto">
                            <div class="stat-icon bg-teal bg-opacity-10 text-teal">
                                <i class="fas fa-boxes"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card dashboard-card stat-card warning">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col">
                            <div class="text-muted text-uppercase small mb-1">Low Stock Alerts</div>
                            <div class="h4 mb-0 fw-bold">{{ $lowStockCount }}</div>
                            <div class="mt-2">
                                <span class="text-warning small">
                                    <i class="fas fa-exclamation-triangle me-1"></i>Require immediate attention
                                </span>
                            </div>
                            @if($criticalCount > 0)
                            <div class="small text-danger mt-1">
                                <i class="fas fa-fire me-1"></i>{{ $criticalCount }} critical items
                            </div>
                            @endif
                        </div>
                        <div class="col-auto">
                            <div class="stat-icon bg-warning bg-opacity-10 text-warning">
                                <i class="fas fa-exclamation-triangle"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card dashboard-card stat-card purple">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col">
                            <div class="text-muted text-uppercase small mb-1">Pending Orders</div>
                            <div class="h4 mb-0 fw-bold">{{ $pendingOrders }}</div>
                            <div class="mt-2">
                                <span class="text-purple small">
                                    <i class="fas fa-shopping-cart me-1"></i>{{ $pendingOrdersValue }} total value
                                </span>
                            </div>
                            @if($overdueOrders > 0)
                            <div class="small text-danger mt-1">
                                <i class="fas fa-clock me-1"></i>{{ $overdueOrders }} overdue
                            </div>
                            @endif
                        </div>
                        <div class="col-auto">
                            <div class="stat-icon bg-purple bg-opacity-10 text-purple">
                                <i class="fas fa-clipboard-check"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Action Bar -->
        <div class="action-bar">
            <div class="action-bar-header">
                <h3 class="action-bar-title">
                    <i class="fas fa-tools me-2"></i>Inventory Management
                </h3>
                <div class="action-bar-actions">
                    <!-- Category Management Button -->
                    <a href="/categories" class="action-btn action-btn-secondary" title="Manage Categories">
                        <i class="fas fa-tags me-1"></i>
                        Categories
                    </a>

                    <!-- Transaction History -->
                    <a href="{{ route('inventory.transactions') }}" class="action-btn action-btn-outline">
                        <i class="fas fa-history me-1"></i>
                        Transaction History
                    </a>

                    <!-- Purchase Orders -->
                    <a href="{{ route('purchase-orders.index') }}" class="action-btn action-btn-secondary">
                        <i class="fas fa-clipboard-list me-1"></i>
                        Purchase Orders
                    </a>

                    <!-- Export Dropdown -->
                    <div class="dropdown">
                        <button class="action-btn action-btn-outline" type="button" data-bs-toggle="modal" data-bs-target="#pdfExportModal">
                            <i class="fas fa-file-pdf me-1 text-danger"></i>
                            Export PDF
                        </button>
                    </div>

                    <!-- Add New Item -->
                    <button class="action-btn action-btn-primary" data-bs-toggle="modal" data-bs-target="#addItemModal">
                        <i class="fas fa-plus me-1"></i>
                        Add New Item
                    </button>
                </div>
            </div>
            
            <!-- Quick Stats Row -->
            <div class="row mt-3">
                <div class="col-md-3">
                    <div class="d-flex align-items-center">
                        <div class="me-3">
                            <span class="stock-indicator stock-good"></span>
                        </div>
                        <div>
                            <div class="small text-muted">In Stock</div>
                            <div class="fw-bold">{{ $inStockCount }} items</div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="d-flex align-items-center">
                        <div class="me-3">
                            <span class="stock-indicator stock-warning"></span>
                        </div>
                        <div>
                            <div class="small text-muted">Low Stock</div>
                            <div class="fw-bold">{{ $lowStockCount }} items</div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="d-flex align-items-center">
                        <div class="me-3">
                            <span class="stock-indicator stock-danger"></span>
                        </div>
                        <div>
                            <div class="small text-muted">Out of Stock</div>
                            <div class="fw-bold">{{ $outOfStockCount }} items</div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="d-flex align-items-center">
                        <div class="me-3">
                            <i class="fas fa-truck text-purple"></i>
                        </div>
                        <div>
                            <div class="small text-muted">Avg. Delivery Time</div>
                            <div class="fw-bold">{{ $avgDeliveryTime }} days</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filters -->
        <div class="filter-card">
            <form method="GET" action="{{ route('inventory.index') }}" id="filterForm">
                <div class="row g-3">
                    <div class="col-md-2">
                        <label class="form-label small text-muted">Search</label>
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-search"></i></span>
                            <input type="text" class="form-control" placeholder="Item name, SKU..." name="search" value="{{ request('search') }}">
                        </div>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label small text-muted">Category</label>
                        <select class="form-select" name="category" id="categoryFilter">
                            <option value="">All Categories</option>
                            @foreach($categories as $category)
                                <option value="{{ $category }}" {{ request('category') == $category ? 'selected' : '' }}>
                                    {{ $category }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label small text-muted">Department</label>
                        <select class="form-select" name="department">
                            <option value="">All Departments</option>
                            @foreach(config('system_departments.options', []) as $deptValue => $deptLabel)
                                <option value="{{ $deptValue }}" {{ request('department') == $deptValue ? 'selected' : '' }}>
                                    {{ $deptLabel }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label small text-muted">Status</label>
                        <select class="form-select" name="status">
                            <option value="">All Status</option>
                            <option value="active" {{ request('status') == 'active' ? 'selected' : '' }}>Active</option>
                            <option value="inactive" {{ request('status') == 'inactive' ? 'selected' : '' }}>Inactive</option>
                            <option value="low_stock" {{ request('status') == 'low_stock' ? 'selected' : '' }}>Low Stock</option>
                            <option value="out_of_stock" {{ request('status') == 'out_of_stock' ? 'selected' : '' }}>Out of Stock</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label small text-muted">Sort By</label>
                        <select class="form-select" name="sort">
                            <option value="name_asc" {{ request('sort') == 'name_asc' ? 'selected' : '' }}>Name A-Z</option>
                            <option value="name_desc" {{ request('sort') == 'name_desc' ? 'selected' : '' }}>Name Z-A</option>
                            <option value="quantity_asc" {{ request('sort') == 'quantity_asc' ? 'selected' : '' }}>Quantity Low-High</option>
                            <option value="quantity_desc" {{ request('sort') == 'quantity_desc' ? 'selected' : '' }}>Quantity High-Low</option>
                            <option value="value_desc" {{ request('sort') == 'value_desc' ? 'selected' : '' }}>Highest Value</option>
                            <option value="recent" {{ request('sort') == 'recent' ? 'selected' : '' }}>Recently Added</option>
                        </select>
                    </div>
                    <div class="col-md-2 d-flex align-items-end">
                        <div class="d-flex gap-2 w-100">
                            <button type="submit" class="btn btn-primary flex-fill">
                                <i class="fas fa-filter me-2"></i>Apply
                            </button>
                            <a href="{{ route('inventory.index') }}" class="btn btn-outline-secondary">
                                <i class="fas fa-redo"></i>
                            </a>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <!-- Category Management Alert -->
        @if($categories->isEmpty())
        <div class="alert alert-warning fade-in" role="alert">
            <div class="d-flex align-items-center">
                <i class="fas fa-exclamation-triangle fa-2x me-3"></i>
                <div>
                    <h5 class="alert-heading mb-1">No Categories Found</h5>
                    <p class="mb-0">You need to set up categories before adding inventory items. Categories are used to organize both inventory items and vendors.</p>
                    <div class="mt-2">
                        <a href="/categories" class="btn btn-sm btn-warning">
                            <i class="fas fa-plus me-1"></i>Create Categories
                        </a>
                        <a href="#" class="btn btn-sm btn-outline-warning ms-2" data-bs-toggle="modal" data-bs-target="#categoryHelpModal">
                            <i class="fas fa-question-circle me-1"></i>Learn More
                        </a>
                    </div>
                </div>
            </div>
        </div>
        @endif

        <!-- Tabs Navigation -->
        <ul class="nav nav-tabs mb-4" id="inventoryTabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="all-tab" data-bs-toggle="tab" data-bs-target="#all" type="button" role="tab">
                    <i class="fas fa-boxes me-2"></i>All Items
                    <span class="badge bg-primary ms-2">{{ $items->total() }}</span>
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="low-stock-tab" data-bs-toggle="tab" data-bs-target="#low-stock" type="button" role="tab">
                    <i class="fas fa-exclamation-triangle me-2"></i>Low Stock
                    <span class="badge bg-warning ms-2">{{ $lowStockCount }}</span>
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="recent-tab" data-bs-toggle="tab" data-bs-target="#recent" type="button" role="tab">
                    <i class="fas fa-history me-2"></i>Recent Activity
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="categories-tab" data-bs-toggle="tab" data-bs-target="#categories" type="button" role="tab">
                    <i class="fas fa-tags me-2"></i>Categories
                    <span class="badge bg-success ms-2">{{ is_array($categories) ? count($categories) : $categories->count() }}</span>
                </button>
            </li>
        </ul>

        <!-- Tabs Content -->
        <div class="tab-content" id="inventoryTabsContent">
            <!-- All Items Tab -->
            <div class="tab-pane fade show active" id="all" role="tabpanel">
                <div class="card dashboard-card">
                    <div class="card-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <h5 class="m-0">
                                <i class="fas fa-list me-2"></i>Inventory Items
                                <span class="badge bg-primary ms-2">{{ $items->total() }}</span>
                            </h5>
                            <div class="d-flex gap-2">
                                <a href="/categories" class="btn btn-sm btn-success" title="Manage Categories">
                                    <i class="fas fa-tags me-1"></i>Categories
                                </a>
                                <button class="btn btn-sm btn-outline-primary" onclick="toggleColumnVisibility()">
                                    <i class="fas fa-columns me-1"></i>Columns
                                </button>
                                <button class="btn btn-sm btn-outline-success" onclick="printInventory()">
                                    <i class="fas fa-print me-1"></i>Print
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        @if(session('success'))
                            <div class="alert alert-success alert-dismissible fade show" role="alert">
                                <i class="fas fa-check-circle me-2"></i>{{ session('success') }}
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        @endif

                        @if(session('error'))
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <i class="fas fa-exclamation-circle me-2"></i>{{ session('error') }}
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        @endif

                        @if(session('category_sync'))
                            <div class="alert alert-info alert-dismissible fade show" role="alert">
                                <i class="fas fa-sync-alt me-2"></i>{{ session('category_sync') }}
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        @endif

                        @if(isset($reorderItems) && $reorderItems->count() > 0)
                            <div class="alert alert-warning d-flex justify-content-between align-items-start flex-wrap gap-2" role="alert">
                                <div>
                                    <strong><i class="fas fa-bell me-2"></i>Reorder Alerts ({{ $reorderItems->count() }})</strong>
                                    <div class="small mt-1">
                                        @foreach($reorderItems as $reorderItem)
                                            <div>
                                                {{ $reorderItem->name }}: {{ $reorderItem->quantity }} {{ $reorderItem->unit ?? 'units' }}
                                                (reorder at {{ $reorderItem->reorder_point ?? $reorderItem->min_stock }})
                                            </div>
                                        @endforeach
                                    </div>
                                </div>
                                <div class="d-flex flex-wrap gap-1">
                                    @foreach($reorderItems as $reorderItem)
                                        <a href="{{ route('inventory.order.form', $reorderItem->id) }}" class="btn btn-sm btn-outline-warning">
                                            Order {{ \Illuminate\Support\Str::limit($reorderItem->name, 12) }}
                                        </a>
                                    @endforeach
                                </div>
                            </div>
                        @endif

                        @if(isset($recentIssues) && $recentIssues->count() > 0)
                            <div class="card border-0 shadow-sm mb-3">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <h6 class="mb-0"><i class="fas fa-hand-holding me-2 text-danger"></i>Recent Stock Issues</h6>
                                        <small class="text-muted">Who took what and where it went</small>
                                    </div>
                                    <div class="table-responsive">
                                        <table class="table table-sm mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Item</th>
                                                    <th>Qty</th>
                                                    <th>Issued To</th>
                                                    <th>Department</th>
                                                    <th>Reason</th>
                                                    <th>Status</th>
                                                    <th>By</th>
                                                    <th>When</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                @foreach($recentIssues as $issue)
                                                    <tr>
                                                        <td>{{ $issue->item->name ?? 'N/A' }}</td>
                                                        <td>{{ $issue->quantity }} {{ $issue->unit ?? 'units' }}</td>
                                                        <td>{{ $issue->issued_to_name }}</td>
                                                        <td>{{ $issue->issued_to_department ?: '-' }}</td>
                                                        <td>{{ $issue->reason }}</td>
                                                        <td>
                                                            @if($issue->status === 'pending')
                                                                <span class="badge bg-warning text-dark">Pending</span>
                                                            @elseif($issue->status === 'approved')
                                                                <span class="badge bg-primary">Approved</span>
                                                            @elseif($issue->status === 'issued')
                                                                <span class="badge bg-success">Issued</span>
                                                            @else
                                                                <span class="badge bg-secondary">Rejected</span>
                                                            @endif
                                                        </td>
                                                        <td>{{ $issue->issuer->name ?? 'System' }}</td>
                                                        <td>{{ optional($issue->issued_at)->diffForHumans() }}</td>
                                                        <td>
                                                            @if($issue->status === 'pending')
                                                                <div class="d-flex gap-1">
                                                                    <form method="POST" action="{{ route('inventory.issues.approve', $issue->id) }}">
                                                                        @csrf
                                                                        <button class="btn btn-sm btn-outline-primary">Approve</button>
                                                                    </form>
                                                                    <form method="POST" action="{{ route('inventory.issues.reject', $issue->id) }}">
                                                                        @csrf
                                                                        <input type="hidden" name="rejection_reason" value="Rejected from dashboard">
                                                                        <button class="btn btn-sm btn-outline-danger">Reject</button>
                                                                    </form>
                                                                </div>
                                                            @elseif($issue->status === 'approved')
                                                                <form method="POST" action="{{ route('inventory.issues.issue', $issue->id) }}">
                                                                    @csrf
                                                                    <button class="btn btn-sm btn-danger">Issue Now</button>
                                                                </form>
                                                            @else
                                                                <span class="text-muted">-</span>
                                                            @endif
                                                        </td>
                                                    </tr>
                                                @endforeach
                                            </tbody>
                                        </table>
                                    </div>
                                    <div class="mt-2 text-end">
                                        <a href="{{ route('inventory.issues') }}" class="btn btn-sm btn-outline-secondary">
                                            View Full Issue Log
                                        </a>
                                    </div>
                                </div>
                            </div>
                        @endif

                        <div class="table-responsive">
                            <table class="table table-hover" id="inventoryTable">
                                <thead>
                                    <tr>
                                        <th>Item</th>
                                        <th class="toggle-column">SKU</th>
                                        <th>Category</th>
                                        <th>Current Stock</th>
                                        <th class="toggle-column">Par Level</th>
                                        <th>Unit Cost</th>
                                        <th>Total Value</th>
                                        <th>Status</th>
                                        <th>Last Updated</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @forelse($items as $item)
                                        <tr class="{{ $item->stock_status == 'in_stock' ? 'inventory-status-good' : ($item->stock_status == 'low_stock' ? 'inventory-status-warning' : 'inventory-status-danger') }} fade-in">
                                            <td>
                                                <div class="d-flex align-items-center">
                                                    <span class="stock-indicator stock-{{ $item->stock_status == 'in_stock' ? 'good' : ($item->stock_status == 'low_stock' ? 'warning' : 'danger') }}"></span>
                                                    <div>
                                                        <strong class="cursor-pointer text-underline-hover" onclick="showItemDetails({{ $item->id }})">
                                                            {{ $item->name }}
                                                        </strong>
                                                        @if($item->description)
                                                            <br><small class="text-muted">{{ Str::limit($item->description, 50) }}</small>
                                                        @endif
                                                        @if($item->department)
                                                            <div class="mt-1">
                                                                <span class="department-badge">
                                                                    <i class="fas fa-building me-1"></i>{{ ucfirst($item->department) }}
                                                                </span>
                                                            </div>
                                                        @endif
                                                    </div>
                                                </div>
                                            </td>
                                            <td class="toggle-column">
                                                <code>{{ $item->sku ?? 'N/A' }}</code>
                                            </td>
                                            <td>
                                                @if($item->category)
                                                    @if(is_object($item->category))
                                                        <span class="category-badge">
                                                            <i class="fas fa-tag me-1"></i>{{ $item->category->name }}
                                                        </span>
                                                    @else
                                                        <span class="badge bg-light text-dark">
                                                            <i class="fas fa-tag me-1"></i>{{ $item->category }}
                                                        </span>
                                                    @endif
                                                @else
                                                    <span class="badge bg-secondary">No Category</span>
                                                @endif
                                            </td>
                                            <td>
                                                <div class="d-flex align-items-center">
                                                    <strong>{{ $item->quantity }}</strong>
                                                    <small class="text-muted ms-1">{{ $item->unit ?? 'units' }}</small>
                                                    @if($item->quantity > 0 && $item->min_stock > 0)
                                                        <div class="ms-2" style="width: 60px;">
                                                            <div class="progress progress-thin">
                                                                @php
                                                                    $percentage = min(100, ($item->quantity / $item->min_stock) * 100);
                                                                    $color = $percentage >= 150 ? 'bg-success' : ($percentage >= 100 ? 'bg-primary' : ($percentage >= 50 ? 'bg-warning' : 'bg-danger'));
                                                                @endphp
                                                                <div class="progress-bar {{ $color }}" style="width: {{ $percentage }}%"></div>
                                                            </div>
                                                        </div>
                                                    @endif
                                                </div>
                                            </td>
                                            <td class="toggle-column">{{ $item->min_stock }}</td>
                                            <td>UGX {{ number_format($item->unit_price, 0) }}</td>
                                            <td>
                                                <strong class="{{ $item->total_value > 1000000 ? 'text-danger' : 'text-dark' }}">
                                                    UGX {{ number_format($item->total_value, 0) }}
                                                </strong>
                                            </td>
                                            <td>
                                                @if($item->stock_status == 'in_stock')
                                                    <span class="status-badge bg-success">In Stock</span>
                                                @elseif($item->stock_status == 'low_stock')
                                                    <span class="status-badge bg-warning text-dark">Low Stock</span>
                                                @else
                                                    <span class="status-badge bg-danger">Out of Stock</span>
                                                @endif
                                            </td>
                                            <td>
                                                <small class="text-muted">
                                                    {{ $item->updated_at->diffForHumans() }}
                                                </small>
                                            </td>
                                            <td>
                                                <div class="item-action-buttons">
                                                    <button class="btn btn-sm btn-outline-primary" type="button" onclick="showItemDetails({{ $item->id }})" title="Edit">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    @if($item->stock_status == 'low_stock' || $item->stock_status == 'out_of_stock')
                                                        <a href="{{ route('inventory.order.form', $item->id) }}" class="btn btn-sm btn-outline-warning" title="Order More">
                                                            <i class="fas fa-shopping-cart"></i>
                                                        </a>
                                                    @endif
                                                    <div class="dropdown">
                                                        <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" data-bs-display="static">
                                                            <i class="fas fa-ellipsis-v"></i>
                                                        </button>
                                                        <ul class="dropdown-menu dropdown-menu-end">
                                                            <li>
                                                                <a class="dropdown-item" href="#" onclick="showItemDetails({{ $item->id }})">
                                                                    <i class="fas fa-eye me-2"></i>View Details
                                                                </a>
                                                            </li>
                                                            <li>
                                                                <a class="dropdown-item" href="#" onclick="openQuickAdjust({{ $item->id }}); return false;">
                                                                    <i class="fas fa-exchange-alt me-2"></i>Adjust Stock
                                                                </a>
                                                            </li>
                                                            <li>
                                                                <a class="dropdown-item" href="{{ route('inventory.transactions.item', $item->id) }}">
                                                                    <i class="fas fa-history me-2"></i>View History
                                                                </a>
                                                            </li>
                                                            <li><hr class="dropdown-divider"></li>
                                                            <li>
                                                                <form action="{{ route('inventory.toggle-status', $item->id) }}" method="POST" class="d-inline">
                                                                    @csrf
                                                                    @method('PATCH')
                                                                    <button type="submit" class="dropdown-item">
                                                                        <i class="fas fa-power-off me-2"></i>
                                                                        {{ $item->active ? 'Deactivate' : 'Activate' }}
                                                                    </button>
                                                                </form>
                                                            </li>
                                                        </ul>
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>
                                    @empty
                                        <tr>
                                            <td colspan="10" class="text-center py-4">
                                                <div class="text-muted">
                                                    <i class="fas fa-box-open fa-3x mb-3"></i>
                                                    <h5>No inventory items found</h5>
                                                    <p>Start by adding your first inventory item</p>
                                                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addItemModal">
                                                        <i class="fas fa-plus me-2"></i>Add First Item
                                                    </button>
                                                    @if($categories->isEmpty())
                                                    <div class="mt-3">
                                                        <a href="/categories" class="btn btn-warning">
                                                            <i class="fas fa-tags me-2"></i>Set Up Categories First
                                                        </a>
                                                    </div>
                                                    @endif
                                                </div>
                                            </td>
                                        </tr>
                                    @endforelse
                                </tbody>
                            </table>
                        </div>
                        
                        <!-- Pagination -->
                        @if($items->hasPages())
                        <div class="d-flex justify-content-between align-items-center mt-4">
                            <div class="text-muted">
                                Showing {{ $items->firstItem() }} to {{ $items->lastItem() }} of {{ $items->total() }} items
                            </div>
                            <nav>
                                {{ $items->links() }}
                            </nav>
                        </div>
                        @endif
                    </div>
                </div>
            </div>

            <!-- Low Stock Tab -->
            <div class="tab-pane fade" id="low-stock" role="tabpanel">
                <div class="card dashboard-card">
                    <div class="card-header">
                        <h5 class="m-0">
                            <i class="fas fa-exclamation-triangle me-2"></i>Low Stock Items
                            <span class="badge bg-warning ms-2">{{ $lowStockItems->count() }}</span>
                        </h5>
                    </div>
                    <div class="card-body">
                        @if($lowStockItems->isNotEmpty())
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>Item</th>
                                            <th>Category</th>
                                            <th>Current Stock</th>
                                            <th>Minimum Required</th>
                                            <th>Urgency</th>
                                            <th>Recommended Order</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @foreach($lowStockItems as $item)
                                            <tr class="inventory-status-warning">
                                                <td>
                                                    <strong>{{ $item->name }}</strong>
                                                    <br><small class="text-muted">{{ $item->sku ?? 'N/A' }}</small>
                                                </td>
                                                <td>
                                                    @if($item->category)
                                                        @if(is_object($item->category))
                                                            <span class="badge bg-light text-dark">
                                                                <i class="fas fa-tag me-1"></i>{{ $item->category->name }}
                                                            </span>
                                                        @else
                                                            <span class="badge bg-light text-dark">
                                                                <i class="fas fa-tag me-1"></i>{{ $item->category }}
                                                            </span>
                                                        @endif
                                                    @else
                                                        <span class="badge bg-secondary">No Category</span>
                                                    @endif
                                                </td>
                                                <td>
                                                    <span class="badge bg-{{ $item->quantity == 0 ? 'danger' : 'warning' }}">
                                                        {{ $item->quantity }}
                                                    </span>
                                                </td>
                                                <td>{{ $item->min_stock }}</td>
                                                <td>
                                                    @php
                                                        $percentage = ($item->quantity / $item->min_stock) * 100;
                                                        if($item->quantity == 0) {
                                                            $urgency = 'Critical';
                                                            $color = 'danger';
                                                        } elseif($percentage <= 25) {
                                                            $urgency = 'High';
                                                            $color = 'danger';
                                                        } elseif($percentage <= 50) {
                                                            $urgency = 'Medium';
                                                            $color = 'warning';
                                                        } else {
                                                            $urgency = 'Low';
                                                            $color = 'info';
                                                        }
                                                    @endphp
                                                    <span class="badge bg-{{ $color }}">{{ $urgency }}</span>
                                                </td>
                                                <td>{{ max($item->min_stock * 2 - $item->quantity, $item->min_stock) }} units</td>
                                                <td>
                                                    <a href="{{ route('inventory.order.form', $item->id) }}" class="btn btn-sm btn-warning">
                                                        <i class="fas fa-shopping-cart me-1"></i>Order Now
                                                    </a>
                                                </td>
                                            </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                            </div>
                        @else
                            <div class="text-center py-4">
                                <div class="text-success">
                                    <i class="fas fa-check-circle fa-3x mb-3"></i>
                                    <h5>All items are well stocked!</h5>
                                    <p>No low stock items at the moment.</p>
                                </div>
                            </div>
                        @endif
                    </div>
                </div>
            </div>

            <!-- Recent Activity Tab -->
            <div class="tab-pane fade" id="recent" role="tabpanel">
                <div class="card dashboard-card">
                    <div class="card-header">
                        <h5 class="m-0">
                            <i class="fas fa-history me-2"></i>Recent Activity
                        </h5>
                    </div>
                    <div class="card-body">
                        @if($recentActivities->isNotEmpty())
                            <div class="list-group">
                                @foreach($recentActivities as $activity)
                                    <div class="list-group-item list-group-item-action">
                                        <div class="d-flex w-100 justify-content-between">
                                            <div>
                                                <i class="fas fa-{{ $activity->type == 'in' ? 'arrow-down text-success' : ($activity->type == 'out' ? 'arrow-up text-danger' : 'exchange-alt text-warning') }} me-2"></i>
                                                <strong>{{ $activity->item->name }}</strong>
                                                <span class="badge ms-2 {{ $activity->type == 'in' ? 'transaction-in' : ($activity->type == 'out' ? 'transaction-out' : 'transaction-adjustment') }}">
                                                    {{ strtoupper($activity->type) }}
                                                </span>
                                            </div>
                                            <small class="text-muted">{{ $activity->created_at->diffForHumans() }}</small>
                                        </div>
                                        <div class="mt-2">
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <small class="text-muted">Quantity Change:</small>
                                                    <span class="ms-2 fw-bold {{ $activity->quantity_change > 0 ? 'text-success' : 'text-danger' }}">
                                                        {{ $activity->quantity_change > 0 ? '+' : '' }}{{ $activity->quantity_change }}
                                                    </span>
                                                </div>
                                                <div class="col-md-6">
                                                    <small class="text-muted">By:</small>
                                                    <span class="ms-2">{{ $activity->user->name ?? 'System' }}</span>
                                                </div>
                                            </div>
                                            @if($activity->reference_number)
                                                <div class="mt-1">
                                                    <small class="text-muted">Reference:</small>
                                                    <code class="ms-2">{{ $activity->reference_number }}</code>
                                                </div>
                                            @endif
                                            @if($activity->notes)
                                                <div class="mt-2">
                                                    <small class="text-muted">Notes:</small>
                                                    <p class="mb-0 small">{{ $activity->notes }}</p>
                                                </div>
                                            @endif
                                        </div>
                                    </div>
                                @endforeach
                            </div>
                            <div class="text-center mt-3">
                                <a href="{{ route('inventory.transactions') }}" class="btn btn-outline-primary">
                                    <i class="fas fa-history me-2"></i>View All Transactions
                                </a>
                            </div>
                        @else
                            <div class="text-center py-4">
                                <div class="text-muted">
                                    <i class="fas fa-history fa-3x mb-3"></i>
                                    <h5>No recent activity</h5>
                                    <p>Transactions will appear here as they occur.</p>
                                </div>
                            </div>
                        @endif
                    </div>
                </div>
            </div>

            <!-- Categories Tab -->
            <div class="tab-pane fade" id="categories" role="tabpanel">
                <div class="card dashboard-card">
                    <div class="card-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <h5 class="m-0">
                                <i class="fas fa-tags me-2"></i>Categories Management
                                <span class="badge bg-success ms-2">{{ $categories->count() }}</span>
                            </h5>
                            <div>
                                <a href="/categories" class="btn btn-primary btn-sm">
                                    <i class="fas fa-external-link-alt me-1"></i>Open Category Manager
                                </a>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        @if($categories->isNotEmpty())
                            <div class="row">
                                @foreach($categories as $category)
                                    @php
                                        if (is_object($category)) {
                                            $categoryId = $category->id;
                                            $categoryName = $category->name;
                                            $categoryType = $category->type ?? 'other';
                                            $categoryActive = $category->is_active ?? false;
                                            $categoryDescription = $category->description ?? '';
                                            $categoryUpdatedAt = $category->updated_at ?? now();
                                            $itemCount = $category->items_count ?? 0;
                                        } else {
                                            $categoryId = $loop->index;
                                            $categoryName = $category;
                                            $categoryType = 'other';
                                            $categoryActive = true;
                                            $categoryDescription = '';
                                            $categoryUpdatedAt = now();
                                            $itemCount = 0;
                                        }
                                    @endphp
                                    <div class="col-md-4 mb-4">
                                        <div class="card h-100 hover-shadow">
                                            <div class="card-body">
                                                <div class="d-flex justify-content-between align-items-start mb-3">
                                                    <div>
                                                        <h6 class="card-title mb-1">
                                                            <i class="fas fa-tag me-2 text-primary"></i>{{ $categoryName }}
                                                        </h6>
                                                        <span class="badge bg-{{ $categoryType == 'inventory' ? 'primary' : ($categoryType == 'vendor' ? 'success' : 'secondary') }}">
                                                            {{ ucfirst($categoryType) }}
                                                        </span>
                                                        @if($categoryActive)
                                                            <span class="badge bg-success ms-1">Active</span>
                                                        @else
                                                            <span class="badge bg-secondary ms-1">Inactive</span>
                                                        @endif
                                                    </div>
                                                    <span class="badge bg-light text-dark">
                                                        {{ $itemCount }} items
                                                    </span>
                                                </div>
                                                
                                                @if($categoryDescription)
                                                    <p class="card-text small text-muted mb-3">{{ Str::limit($categoryDescription, 100) }}</p>
                                                @else
                                                    <p class="card-text small text-muted mb-3"><em>No description</em></p>
                                                @endif
                                                
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <small class="text-muted">
                                                        Updated {{ $categoryUpdatedAt->diffForHumans() }}
                                                    </small>
                                                    <div class="btn-group btn-group-sm">
                                                        <a href="/categories?edit={{ $categoryId }}" class="btn btn-outline-primary">
                                                            <i class="fas fa-edit"></i>
                                                        </a>
                                                        <button class="btn btn-outline-danger" onclick="deleteCategory({{ $categoryId }})">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                @endforeach
                            </div>
                            
                            <div class="text-center mt-4">
                                <a href="/categories" class="btn btn-primary">
                                    <i class="fas fa-cog me-2"></i>Manage All Categories
                                </a>
                                <button class="btn btn-success ms-2" data-bs-toggle="modal" data-bs-target="#addCategoryModal">
                                    <i class="fas fa-plus me-2"></i>Add New Category
                                </button>
                            </div>
                        @else
                            <div class="text-center py-5">
                                <div class="text-warning">
                                    <i class="fas fa-tags fa-4x mb-4"></i>
                                    <h4>No Categories Found</h4>
                                    <p class="text-muted mb-4">Categories help organize your inventory items and vendors. Create your first category to get started.</p>
                                    <div class="d-flex justify-content-center gap-3">
                                        <a href="/categories" class="btn btn-primary">
                                            <i class="fas fa-external-link-alt me-2"></i>Open Category Manager
                                        </a>
                                        <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addCategoryModal">
                                            <i class="fas fa-plus me-2"></i>Add Category
                                        </button>
                                    </div>
                                </div>
                            </div>
                        @endif
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Item Modal -->
    <div class="modal fade" id="addItemModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-plus me-2"></i>Add New Inventory Item</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form action="{{ route('inventory.store') }}" method="POST" id="addItemForm">
                    @csrf
                    <div class="modal-body">
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            <strong>Category Requirement:</strong> Items must be assigned to a category. Categories are shared across inventory and vendors for consistency.
                            @if($categories->isEmpty())
                                <div class="mt-2">
                                    <a href="/categories" class="btn btn-sm btn-warning">
                                        <i class="fas fa-plus me-1"></i>Create Categories First
                                    </a>
                                </div>
                            @endif
                        </div>
                        
                        <ul class="nav nav-pills mb-4" id="addItemTabs" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="basic-tab" data-bs-toggle="tab" data-bs-target="#basic" type="button">
                                    <i class="fas fa-info-circle me-2"></i>Basic Info
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="pricing-tab" data-bs-toggle="tab" data-bs-target="#pricing" type="button">
                                    <i class="fas fa-dollar-sign me-2"></i>Pricing & Stock
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="advanced-tab" data-bs-toggle="tab" data-bs-target="#advanced" type="button">
                                    <i class="fas fa-cogs me-2"></i>Advanced
                                </button>
                            </li>
                        </ul>

                        <div class="tab-content" id="addItemTabsContent">
                            <!-- Basic Info Tab -->
                            <div class="tab-pane fade show active" id="basic" role="tabpanel">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="itemName" class="form-label">Item Name *</label>
                                        <input type="text" class="form-control" id="itemName" name="name" required>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="itemSKU" class="form-label">SKU</label>
                                        <input type="text" class="form-control" id="itemSKU" name="sku" placeholder="Auto-generated if empty">
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="itemCategory" class="form-label">Category *</label>
                                        <div class="category-select-wrapper" id="categorySelectWrapper">
                                            <select class="form-select" id="itemCategory" name="category" required {{ $categories->isEmpty() ? 'disabled' : '' }}>
                                                <option value="">Select Category</option>
                                                @foreach($categories as $category)
                                                    @php
                                                        $categoryValue = is_object($category) ? ($category->category ?? $category) : $category;
                                                    @endphp
                                                    <option value="{{ $categoryValue }}">{{ $categoryValue }}</option>
                                                @endforeach
                                            </select>
                                            <div class="loading-categories">
                                                <div class="spinner-border spinner-border-sm text-primary" role="status">
                                                    <span class="visually-hidden">Loading...</span>
                                                </div>
                                            </div>
                                        </div>
                                        @if($categories->isEmpty())
                                            <small class="text-danger">No categories available. <a href="/categories">Create categories first</a>.</small>
                                        @endif
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="itemDepartment" class="form-label">Department</label>
                                        <select class="form-select" id="itemDepartment" name="department">
                                            <option value="">Select Department</option>
                                            @foreach(config('system_departments.options', []) as $deptValue => $deptLabel)
                                                <option value="{{ $deptValue }}">{{ $deptLabel }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <label for="itemDescription" class="form-label">Description</label>
                                    <textarea class="form-control" id="itemDescription" name="description" rows="3"></textarea>
                                </div>
                                <div class="alert alert-light border">
                                    <i class="fas fa-lightbulb text-warning me-2"></i>
                                    <small>Can't find the right category? <a href="#" data-bs-toggle="modal" data-bs-target="#addCategoryModal">Create a new one</a></small>
                                </div>
                            </div>

                            <!-- Pricing & Stock Tab -->
                            <div class="tab-pane fade" id="pricing" role="tabpanel">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="itemUnitPrice" class="form-label">Unit Cost (UGX) *</label>
                                        <input type="number" step="0.01" class="form-control" id="itemUnitPrice" name="unit_price" min="0" required>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="itemSellingPrice" class="form-label">Selling Price (UGX)</label>
                                        <input type="number" step="0.01" class="form-control" id="itemSellingPrice" name="selling_price" min="0">
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="itemQuantity" class="form-label">Initial Quantity *</label>
                                        <input type="number" class="form-control" id="itemQuantity" name="quantity" min="0" required>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="itemMinStock" class="form-label">Minimum Stock Level *</label>
                                        <input type="number" class="form-control" id="itemMinStock" name="min_stock" min="0" required>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="itemMaxStock" class="form-label">Maximum Stock Level</label>
                                        <input type="number" class="form-control" id="itemMaxStock" name="max_stock" min="0">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="itemReorderPoint" class="form-label">Reorder Point</label>
                                        <input type="number" class="form-control" id="itemReorderPoint" name="reorder_point" min="0">
                                    </div>
                                </div>
                            </div>

                            <!-- Advanced Tab -->
                            <div class="tab-pane fade" id="advanced" role="tabpanel">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="itemSupplier" class="form-label">Primary Supplier</label>
                                        <select class="form-select" id="itemSupplier" name="supplier_id">
                                            <option value="">Select Supplier</option>
                                            @foreach($suppliers as $supplier)
                                                <option value="{{ $supplier->id }}">{{ $supplier->company }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="itemLocation" class="form-label">Storage Location</label>
                                        <input type="text" class="form-control" id="itemLocation" name="location">
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="itemUnit" class="form-label">Unit of Measure</label>
                                        <select class="form-select" id="itemUnit" name="unit">
                                            @foreach(config('inventory_units.options', []) as $unitValue => $unitLabel)
                                                <option value="{{ $unitValue }}" {{ $unitValue === 'pieces' ? 'selected' : '' }}>{{ $unitLabel }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="itemPurchaseUnit" class="form-label">Purchase Unit</label>
                                        <select class="form-select" id="itemPurchaseUnit" name="purchase_unit">
                                            <option value="">Same as Unit of Measure</option>
                                            @foreach(config('inventory_units.options', []) as $unitValue => $unitLabel)
                                                <option value="{{ $unitValue }}">{{ $unitLabel }}</option>
                                            @endforeach
                                        </select>
                                        <small class="text-muted">Example: purchase in cartons, stock in bottles/pieces.</small>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="itemUnitConversionFactor" class="form-label">Units per Purchase Unit</label>
                                        <input type="number" step="0.001" min="0.001" class="form-control" id="itemUnitConversionFactor" name="unit_conversion_factor" placeholder="e.g. 12">
                                        <small class="text-muted">For carton/dozen use 12.</small>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="itemExpiryDate" class="form-label">Expiry Date (if applicable)</label>
                                        <input type="date" class="form-control" id="itemExpiryDate" name="expiry_date">
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <label for="itemNotes" class="form-label">Additional Notes</label>
                                    <textarea class="form-control" id="itemNotes" name="notes" rows="3"></textarea>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary" id="saveItemBtn" {{ $categories->isEmpty() ? 'disabled' : '' }}>
                            <i class="fas fa-save me-2"></i>Save Item
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- PDF Export Modal -->
    <div class="modal fade pdf-export-modal" id="pdfExportModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-file-pdf me-2"></i>Export Inventory as PDF</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form action="{{ route('inventory.export.pdf') }}" method="POST" id="pdfExportForm">
                    @csrf
                    <div class="modal-body">
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <div class="card pdf-option-card selected" data-report-type="summary">
                                    <div class="card-body text-center">
                                        <div class="pdf-option-icon bg-primary bg-opacity-10 text-primary">
                                            <i class="fas fa-chart-bar"></i>
                                        </div>
                                        <h6 class="card-title">Summary Report</h6>
                                        <p class="small text-muted">Quick overview with key statistics and charts</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="card pdf-option-card" data-report-type="detailed">
                                    <div class="card-body text-center">
                                        <div class="pdf-option-icon bg-success bg-opacity-10 text-success">
                                            <i class="fas fa-list-alt"></i>
                                        </div>
                                        <h6 class="card-title">Detailed Report</h6>
                                        <p class="small text-muted">Complete inventory list with all item details</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <input type="hidden" name="report_type" id="reportType" value="summary">
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="pdfTitle" class="form-label">Report Title</label>
                                <input type="text" class="form-control" id="pdfTitle" name="title" value="Inventory Report - {{ date('F j, Y') }}">
                            </div>
                            <div class="col-md-6">
                                <label for="pdfOrientation" class="form-label">Page Orientation</label>
                                <select class="form-select" id="pdfOrientation" name="orientation">
                                    <option value="portrait">Portrait</option>
                                    <option value="landscape">Landscape</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="pdfDateRange" class="form-label">Date Range</label>
                                <select class="form-select" id="pdfDateRange" name="date_range">
                                    <option value="all">All Time</option>
                                    <option value="today">Today</option>
                                    <option value="week">This Week</option>
                                    <option value="month">This Month</option>
                                    <option value="quarter">This Quarter</option>
                                    <option value="year">This Year</option>
                                    <option value="custom">Custom Range</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="pdfSortBy" class="form-label">Sort By</label>
                                <select class="form-select" id="pdfSortBy" name="sort_by">
                                    <option value="name">Item Name</option>
                                    <option value="category">Category</option>
                                    <option value="quantity">Quantity</option>
                                    <option value="value">Total Value</option>
                                    <option value="date">Date Added</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="row mb-3" id="customDateRange" style="display: none;">
                            <div class="col-md-6">
                                <label for="pdfStartDate" class="form-label">Start Date</label>
                                <input type="date" class="form-control" id="pdfStartDate" name="start_date">
                            </div>
                            <div class="col-md-6">
                                <label for="pdfEndDate" class="form-label">End Date</label>
                                <input type="date" class="form-control" id="pdfEndDate" name="end_date">
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-12">
                                <label class="form-label">Include Sections</label>
                                <div class="row">
                                    <div class="col-md-4">
                                                Charts & Graphs
                                            </label>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="includeLowStock" name="include_low_stock" checked>
                                            <label class="form-check-label" for="includeLowStock">
                                                Low Stock Alert
                                            </label>
                                        </div>
                                    </div>
                                    <input type="hidden" name="report_type" id="reportType" value="detailed">
                            </div>
                        </div>
                        
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            The PDF will be generated with your hotel logo and branding. You can download it immediately after generation.
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-danger" id="generatePdfBtn">
                            <i class="fas fa-file-pdf me-2"></i>Generate PDF
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Add Category Modal (Inline) -->
    <div class="modal fade" id="addCategoryModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-plus me-2"></i>Add New Category</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="addCategoryFormInline">
                    @csrf
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="categoryNameInline" class="form-label">Category Name *</label>
                            <input type="text" class="form-control" id="categoryNameInline" name="name" required>
                        </div>
                        <div class="mb-3">
                            <label for="categoryDescriptionInline" class="form-label">Description</label>
                            <textarea class="form-control" id="categoryDescriptionInline" name="description" rows="2"></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="categoryTypeInline" class="form-label">Type *</label>
                            <select class="form-select" id="categoryTypeInline" name="type" required>
                                <option value="inventory">Inventory</option>
                                <option value="vendor">Vendor</option>
                                <option value="product">Product</option>
                                <option value="service">Service</option>
                                <option value="other">Other</option>
                            </select>
                            <small class="text-muted">Categories marked as "inventory" or "product" will appear in inventory item selection.</small>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary" id="saveCategoryBtn">
                            <i class="fas fa-save me-2"></i>Save Category
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Category Help Modal -->
    <div class="modal fade" id="categoryHelpModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-question-circle me-2"></i>About Categories</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="card h-100">
                                <div class="card-body">
                                    <h6><i class="fas fa-boxes text-primary me-2"></i>Inventory Categories</h6>
                                    <p class="small">Categories with type "inventory" or "product" are used to organize inventory items. Examples:</p>
                                    <ul class="small">
                                        <li>Food & Beverage</li>
                                        <li>Cleaning Supplies</li>
                                        <li>Linens & Bedding</li>
                                        <li>Maintenance Tools</li>
                                        <li>Office Supplies</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card h-100">
                                <div class="card-body">
                                    <h6><i class="fas fa-truck text-success me-2"></i>Vendor Categories</h6>
                                    <p class="small">Categories with type "vendor" are used to organize suppliers. Examples:</p>
                                    <ul class="small">
                                        <li>Food Suppliers</li>
                                        <li>Cleaning Services</li>
                                        <li>Maintenance Contractors</li>
                                        <li>Linen Services</li>
                                        <li>Equipment Rental</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="alert alert-info mt-3">
                        <i class="fas fa-lightbulb me-2"></i>
                        <strong>Pro Tip:</strong> Use consistent category names across inventory and vendors to easily match items with their suppliers.
                    </div>
                </div>
                <div class="modal-footer">
                    <a href="/categories" class="btn btn-primary">
                        <i class="fas fa-external-link-alt me-2"></i>Go to Category Manager
                    </a>
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Quick Stock Adjustment Modal -->
    <div class="modal fade" id="quickAdjustModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-exchange-alt me-2"></i>Quick Stock Adjustment</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form action="{{ route('inventory.quick-adjust') }}" method="POST">
                    @csrf
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="adjustItem" class="form-label">Select Item</label>
                            <select class="form-select" id="adjustItem" name="item_id" required>
                                <option value="">Select Item</option>
                                @foreach($items as $item)
                                    <option value="{{ $item->id }}">{{ $item->name }} (Current: {{ $item->quantity }})</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="adjustType" class="form-label">Adjustment Type</label>
                            <select class="form-select" id="adjustType" name="type" required>
                                <option value="add">Add Stock</option>
                                <option value="remove">Remove Stock</option>
                                <option value="set">Set Stock Level</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="adjustQuantity" class="form-label">Quantity</label>
                            <input type="number" class="form-control" id="adjustQuantity" name="quantity" min="1" required>
                        </div>
                        <div class="mb-3">
                            <label for="adjustReason" class="form-label">Reason</label>
                            <select class="form-select" id="adjustReason" name="reason" required>
                                <option value="restock">Restock</option>
                                <option value="damage">Damage</option>
                                <option value="wastage">Wastage</option>
                                <option value="expiry">Expiry</option>
                                <option value="theft">Theft/Loss</option>
                                <option value="count_adjustment">Count Adjustment</option>
                                <option value="transfer_in">Transfer In</option>
                                <option value="transfer_out">Transfer Out</option>
                                <option value="other">Other</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="adjustNotes" class="form-label">Notes <span class="text-danger">*</span></label>
                            <textarea class="form-control" id="adjustNotes" name="notes" rows="2"></textarea>
                            <small class="text-muted">Required for removal, set-level, and non-restock reasons.</small>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Apply Adjustment</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Issue Stock Modal -->
    <div class="modal fade" id="issueStockModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-hand-holding me-2"></i>Issue Stock</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form action="{{ route('inventory.issue-stock') }}" method="POST">
                    @csrf
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Item</label>
                            <select class="form-select" name="inventory_item_id" required>
                                <option value="">Select Item</option>
                                @foreach($items as $item)
                                    <option value="{{ $item->id }}">{{ $item->name }} (Available: {{ $item->quantity }} {{ $item->unit ?? 'units' }})</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Quantity to Issue</label>
                            <input type="number" class="form-control" name="quantity" min="1" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Issued To (Name)</label>
                            <input type="text" class="form-control" name="issued_to_name" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Department</label>
                            <select class="form-select" name="issued_to_department">
                                <option value="">Select Department</option>
                                @foreach(config('system_departments.options', []) as $deptValue => $deptLabel)
                                    <option value="{{ $deptLabel }}">{{ $deptLabel }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Reason</label>
                            <select class="form-select" name="reason" required>
                                <option value="kitchen_usage">Kitchen Usage</option>
                                <option value="housekeeping_usage">Housekeeping Usage</option>
                                <option value="maintenance_usage">Maintenance Usage</option>
                                <option value="bar_service">Bar Service</option>
                                <option value="wastage">Wastage</option>
                                <option value="other">Other</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Notes</label>
                            <textarea class="form-control" name="notes" rows="2"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-danger"><i class="fas fa-check me-1"></i>Submit for Approval</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Edit Item Modals (Dynamically Loaded) -->
    <div id="editModalsContainer"></div>

    <!-- JavaScript -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize date pickers
            flatpickr('.date-input', {
                dateFormat: 'Y-m-d',
                minDate: 'today'
            });

            // Initialize flatpickr for PDF date range
            const startDatePicker = flatpickr('#pdfStartDate', {
                dateFormat: 'Y-m-d',
                defaultDate: 'today'
            });
            
            const endDatePicker = flatpickr('#pdfEndDate', {
                dateFormat: 'Y-m-d',
                defaultDate: 'today'
            });

            // Scroll to top functionality
            const scrollToTop = document.getElementById('scrollToTop');
            window.addEventListener('scroll', () => {
                if (window.pageYOffset > 300) {
                    scrollToTop.classList.add('show');
                } else {
                    scrollToTop.classList.remove('show');
                }
            });

            scrollToTop.addEventListener('click', () => {
                window.scrollTo({ top: 0, behavior: 'smooth' });
            });

            // Auto-generate SKU
            document.getElementById('itemName')?.addEventListener('blur', function() {
                const skuField = document.getElementById('itemSKU');
                if (skuField && !skuField.value) {
                    const name = this.value.toLowerCase().replace(/[^a-z0-9]/g, '').substring(0, 8);
                    const random = Math.floor(Math.random() * 1000);
                    skuField.value = name.toUpperCase() + random.toString().padStart(3, '0');
                }
            });

            // Unit conversion presets for purchase units
            const purchaseUnitSelect = document.getElementById('itemPurchaseUnit');
            const conversionInput = document.getElementById('itemUnitConversionFactor');
            if (purchaseUnitSelect && conversionInput) {
                const presetFactors = {
                    dozen: 12,
                    carton: 12,
                    crate: 24
                };
                purchaseUnitSelect.addEventListener('change', function() {
                    const selected = this.value;
                    if (presetFactors[selected]) {
                        conversionInput.value = presetFactors[selected];
                    } else if (!selected) {
                        conversionInput.value = '';
                    }
                });
            }

            // Load categories for item creation
            function loadCategoriesForItemCreation() {
                const categorySelect = document.getElementById('itemCategory');
                const wrapper = document.getElementById('categorySelectWrapper');
                
                if (!categorySelect) return;
                
                wrapper.classList.add('loading');
                
                fetch('/api/categories/inventory')
                    .then(response => response.json())
                    .then(data => {
                        if (data && data.success === false) {
                            throw new Error(data.message || 'Failed to load categories');
                        }

                        const categories = data.categories || data.data || data;
                        if (!Array.isArray(categories)) {
                            throw new Error('Invalid categories response');
                        }

                        const presetNames = Array.isArray(data.preset_names) ? data.preset_names : [];

                        // Clear existing options except the first placeholder
                        while (categorySelect.options.length > 1) {
                            categorySelect.remove(1);
                        }

                        if (categories.length > 0) {
                            const byName = new Map(categories.map(c => [c.name, c]));
                            const suggested = [];
                            presetNames.forEach(name => {
                                const cat = byName.get(name);
                                if (cat) {
                                    suggested.push(cat);
                                }
                            });
                            const suggestedNames = new Set(suggested.map(c => c.name));
                            const other = categories
                                .filter(c => !suggestedNames.has(c.name))
                                .sort((a, b) => (a.name || '').localeCompare(b.name || ''));

                            function appendOptions(optgroupLabel, list) {
                                if (!list.length) {
                                    return;
                                }
                                const optgroup = document.createElement('optgroup');
                                optgroup.label = optgroupLabel;
                                optgroup.className = 'category-option-group';
                                list.forEach(category => {
                                    const option = document.createElement('option');
                                    option.value = category.name;
                                    option.textContent = category.name;
                                    option.className = 'category-option';
                                    option.dataset.categoryId = category.id;
                                    if (category.description) {
                                        option.title = category.description;
                                    }
                                    optgroup.appendChild(option);
                                });
                                categorySelect.appendChild(optgroup);
                            }

                            appendOptions('Suggested examples', suggested);
                            appendOptions('Other categories', other);

                            if (categorySelect.disabled) {
                                categorySelect.disabled = false;
                                document.getElementById('saveItemBtn').disabled = false;
                            }
                        }
                    })
                    .catch(error => {
                        console.error('Error loading categories:', error);
                        showAlert('Failed to load categories. Please try again.', 'danger');
                    })
                    .finally(() => {
                        wrapper.classList.remove('loading');
                    });
            }

            // Load categories when add item modal is shown
            const addItemModal = document.getElementById('addItemModal');
            if (addItemModal) {
                addItemModal.addEventListener('shown.bs.modal', function() {
                    loadCategoriesForItemCreation();
                });
            }

            // PDF Export functionality
            const pdfExportModal = document.getElementById('pdfExportModal');
            if (pdfExportModal) {
                // Report type selection
                const reportCards = document.querySelectorAll('.pdf-option-card');
                const reportTypeInput = document.getElementById('reportType');
                
                reportCards.forEach(card => {
                    card.addEventListener('click', function() {
                        reportCards.forEach(c => c.classList.remove('selected'));
                        this.classList.add('selected');
                        reportTypeInput.value = this.dataset.reportType;
                    });
                });
                
                // Show/hide custom date range
                const dateRangeSelect = document.getElementById('pdfDateRange');
                const customDateRangeDiv = document.getElementById('customDateRange');
                
                dateRangeSelect.addEventListener('change', function() {
                    if (this.value === 'custom') {
                        customDateRangeDiv.style.display = 'flex';
                    } else {
                        customDateRangeDiv.style.display = 'none';
                    }
                });
                
                // PDF form submission
                const pdfExportForm = document.getElementById('pdfExportForm');
                if (pdfExportForm) {
                    pdfExportForm.addEventListener('submit', function(e) {
                        e.preventDefault();
                        
                        const generatePdfBtn = document.getElementById('generatePdfBtn');
                        const originalText = generatePdfBtn.innerHTML;
                        
                        // Show loading overlay
                        document.getElementById('pdfLoadingOverlay').style.display = 'flex';
                        
                        // Disable button and show loading
                        generatePdfBtn.disabled = true;
                        generatePdfBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Generating...';
                        
                        // Submit form via AJAX
                        const formData = new FormData(this);
                        
                        fetch(this.action, {
                            method: 'POST',
                            headers: {
                                'Accept': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || ''
                            },
                            body: formData
                        })
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('Network response was not ok');
                            }
                            return response.blob();
                        })
                        .then(blob => {
                            // Create download link
                            const url = window.URL.createObjectURL(blob);
                            const a = document.createElement('a');
                            a.href = url;
                            
                            // Generate filename
                            const reportType = document.getElementById('reportType').value;
                            const date = new Date().toISOString().split('T')[0];
                            const filename = `inventory-${reportType}-report-${date}.pdf`;
                            a.download = filename;
                            
                            // Trigger download
                            document.body.appendChild(a);
                            a.click();
                            document.body.removeChild(a);
                            window.URL.revokeObjectURL(url);
                            
                            // Show success message
                            showAlert('PDF generated and downloaded successfully!', 'success');
                        })
                        .catch(error => {
                            console.error('Error generating PDF:', error);
                            showAlert('Failed to generate PDF. Please try again.', 'danger');
                        })
                        .finally(() => {
                            // Hide loading overlay
                            document.getElementById('pdfLoadingOverlay').style.display = 'none';
                            
                            // Reset button
                            generatePdfBtn.disabled = false;
                            generatePdfBtn.innerHTML = originalText;
                            
                            // Close modal
                            const modal = bootstrap.Modal.getInstance(pdfExportModal);
                            if (modal) modal.hide();
                        });
                    });
                }
            }

            // Inline category form submission
            const addCategoryFormInline = document.getElementById('addCategoryFormInline');
            if (addCategoryFormInline) {
                addCategoryFormInline.addEventListener('submit', function(e) {
                    e.preventDefault();
                    
                    const saveBtn = document.getElementById('saveCategoryBtn');
                    const originalText = saveBtn.innerHTML;
                    
                    saveBtn.disabled = true;
                    saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Saving...';
                    
                    const formData = new FormData(this);
                    
                    fetch('/categories', {
                        method: 'POST',
                        headers: {
                            'Accept': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || ''
                        },
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // Close modal
                            const modal = bootstrap.Modal.getInstance(document.getElementById('addCategoryModal'));
                            if (modal) modal.hide();
                            
                            // Show success message
                            showAlert('Category added successfully!', 'success');
                            
                            // Reload categories in the add item modal
                            setTimeout(() => {
                                loadCategoriesForItemCreation();
                                // Reset form
                                addCategoryFormInline.reset();
                            }, 1000);
                        } else {
                            showAlert(data.message || 'Failed to add category', 'danger');
                        }
                    })
                    .catch(error => {
                        console.error('Error adding category:', error);
                        showAlert('Failed to add category. Please try again.', 'danger');
                    })
                    .finally(() => {
                        saveBtn.disabled = false;
                        saveBtn.innerHTML = originalText;
                    });
                });
            }

            // Tab switching in add modal
            const addItemTabs = document.querySelectorAll('#addItemTabs button');
            addItemTabs.forEach(tab => {
                tab.addEventListener('click', function() {
                    const target = this.getAttribute('data-bs-target');
                    const activeTab = document.querySelector('.nav-pills .nav-link.active');
                    const activeContent = document.querySelector('.tab-content .tab-pane.active');
                    
                    if (activeTab) activeTab.classList.remove('active');
                    if (activeContent) activeContent.classList.remove('show', 'active');
                    
                    this.classList.add('active');
                    document.querySelector(target).classList.add('show', 'active');
                });
            });

            // Form validation for add item
            const addItemForm = document.getElementById('addItemForm');
            if (addItemForm) {
                addItemForm.addEventListener('submit', function(e) {
                    // Check if category is selected
                    const categorySelect = document.getElementById('itemCategory');
                    if (categorySelect && !categorySelect.value) {
                        e.preventDefault();
                        showAlert('Please select a category for this item.', 'warning');
                        categorySelect.focus();
                        return false;
                    }

                    const minStock = parseInt(document.getElementById('itemMinStock').value) || 0;
                    const maxStock = parseInt(document.getElementById('itemMaxStock').value) || 0;
                    
                    if (maxStock > 0 && minStock > maxStock) {
                        e.preventDefault();
                        showAlert('Minimum stock cannot be greater than maximum stock.', 'warning');
                        return false;
                    }
                    
                    const quantity = parseInt(document.getElementById('itemQuantity').value) || 0;
                    if (maxStock > 0 && quantity > maxStock) {
                        if (!confirm('Initial quantity exceeds maximum stock level. Continue anyway?')) {
                            e.preventDefault();
                            return false;
                        }
                    }
                    
                    // Show loading
                    const saveBtn = document.getElementById('saveItemBtn');
                    const originalText = saveBtn.innerHTML;
                    saveBtn.disabled = true;
                    saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Saving...';
                });
            }

            // Real-time search
            const searchInput = document.querySelector('input[name="search"]');
            if (searchInput) {
                let searchTimeout;
                searchInput.addEventListener('input', function() {
                    clearTimeout(searchTimeout);
                    searchTimeout = setTimeout(() => {
                        this.form.submit();
                    }, 500);
                });
            }

            // Column visibility toggle
            window.toggleColumnVisibility = function() {
                const columns = document.querySelectorAll('.toggle-column');
                columns.forEach(col => {
                    col.classList.toggle('d-none');
                });
            };

            // Print functionality
            window.printInventory = function() {
                const printWindow = window.open('', '_blank');
                printWindow.document.write(`
                    <html>
                    <head>
                        <title>Inventory Report - {{ hotelName() }}</title>
                        <style>
                            body { font-family: Arial, sans-serif; }
                            table { width: 100%; border-collapse: collapse; }
                            th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
                            th { background-color: #f2f2f2; }
                            .header { text-align: center; margin-bottom: 20px; }
                            .date { text-align: right; margin-bottom: 10px; }
                        </style>
                    </head>
                    <body>
                        <div class="header">
                            <h2>{{ hotelName() }} - Inventory Report</h2>
                            <p>Generated on: ${new Date().toLocaleDateString()}</p>
                        </div>
                        ${document.querySelector('#inventoryTable').outerHTML}
                    </body>
                    </html>
                `);
                printWindow.document.close();
                printWindow.print();
            };

            // Load edit modal dynamically
            window.showItemDetails = function(itemId) {
                fetch(`/inventory/${itemId}/details`, {
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('Failed to fetch item details');
                        }
                        return response.text();
                    })
                    .then(html => {
                        if (!html || html.trim().length < 20) {
                            throw new Error('Empty item details response');
                        }
                        const container = document.getElementById('editModalsContainer');
                        container.innerHTML = html;
                        const modalEl = document.getElementById(`itemDetailsModal${itemId}`);
                        if (!modalEl) {
                            throw new Error('Modal markup not found in response');
                        }
                        const modal = new bootstrap.Modal(modalEl);
                        modal.show();
                    })
                    .catch(error => {
                        console.error('Error loading item details:', error);
                        showAlert('Unable to load item details. Please refresh and try again.', 'danger');
                    });
            };

            window.openQuickAdjust = function(itemId) {
                const select = document.getElementById('adjustItem');
                if (select) {
                    select.value = String(itemId);
                }
                const modalEl = document.getElementById('quickAdjustModal');
                if (modalEl) {
                    const modal = new bootstrap.Modal(modalEl);
                    modal.show();
                }
            };

            // Category functions
            window.deleteCategory = function(categoryId) {
                if (confirm('Are you sure you want to delete this category? Items using this category will become uncategorized.')) {
                    fetch(`/categories/${categoryId}`, {
                        method: 'DELETE',
                        headers: {
                            'Accept': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || ''
                        }
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            showAlert('Category deleted successfully!', 'success');
                            setTimeout(() => {
                                window.location.reload();
                            }, 1000);
                        } else {
                            showAlert(data.message || 'Failed to delete category', 'danger');
                        }
                    })
                    .catch(error => {
                        console.error('Error deleting category:', error);
                        showAlert('Failed to delete category. Please try again.', 'danger');
                    });
                }
            };

            // Initialize tooltips
            const tooltipTriggerList = [].slice.call(document.querySelectorAll('[title]'));
            tooltipTriggerList.map(function(tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl);
            });

            // Auto-refresh low stock notifications
            setInterval(() => {
                fetch('/api/inventory/low-stock-count')
                    .then(response => response.json())
                    .then(data => {
                        const badge = document.querySelector('#low-stock-tab .badge');
                        if (badge && data.count != badge.textContent) {
                            badge.textContent = data.count;
                            if (data.count > 0 && !document.querySelector('#low-stock-tab').classList.contains('active')) {
                                badge.classList.add('pulse');
                            } else {
                                badge.classList.remove('pulse');
                            }
                        }
                    });
            }, 30000); // Every 30 seconds

            // Alert function
            function showAlert(message, type = 'success') {
                // Create alert element
                const alertDiv = document.createElement('div');
                alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
                alertDiv.innerHTML = `
                    ${message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                `;
                
                // Insert at the beginning of the main content
                const mainContent = document.querySelector('.main-content');
                if (mainContent) {
                    mainContent.insertBefore(alertDiv, mainContent.firstChild);
                    
                    // Auto remove after 5 seconds
                    setTimeout(() => {
                        if (alertDiv.parentNode) {
                            alertDiv.remove();
                        }
                    }, 5000);
                }
            }
            
            // Load categories on page load if needed
            if (document.getElementById('itemCategory') && document.getElementById('itemCategory').options.length <= 1) {
                loadCategoriesForItemCreation();
            }
        });
    </script>
     <script src="{{ asset('js/theme-applier.js') }}"></script>
</body>
</html>

