<?php $__env->startSection('title', 'Stock Management'); ?>
<?php $__env->startSection('header', 'Stock Management'); ?>
<?php $__env->startSection('subheader', 'Track and manage your product inventory.'); ?>

<?php $__env->startPush('styles'); ?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<script src="https://cdn.tailwindcss.com"></script>
<style>
    .dropdown {
        position: relative;
        display: inline-block;
        width: 100%;
    }
    .dropdown-btn {
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        padding: 12px 16px; /* Increased padding for touch */
        background: white;
        border: 1px solid #d1d5db;
        border-radius: 8px;
        font-size: 16px; /* Larger font for mobile */
        transition: all 0.2s ease;
        @apply hover:border-primary;
    }
    .nested-dropdown .dropdown-item:hover {
        background-color: #e5e7eb;
    }
    .nested-dropdown .dropdown-item:hover {
        @apply border-primary;
    }
    .dropdown-content {
        display: none;
        position: absolute;
        background-color: white;
        width: 100%;
        box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
        border-radius: 8px;
        z-index: 10;
        max-height: 300px;
        overflow-y: auto;
        margin-top: 4px;
    }
    .dropdown-content.show {
        display: block;
    }
    .dropdown-item {
        padding: 12px 16px; /* Increased padding for touch */
        cursor: pointer;
        display: flex;
        align-items: center;
        font-size: 16px; /* Larger font for mobile */
        transition: background-color 0.2s;
    }
    .dropdown-item:hover {
        background-color: #f3f4f6;
    }
    .nested-dropdown-content a.dropdown-item {
        border-radius: 6px;
        margin: 2px 8px;
        padding-left: 1rem; /* 16px */
        width: calc(100% - 16px);
    }

    .dropdown-item.selected {
        @apply bg-primary/10 text-primary;
    }
    .status-badge {
        padding: 6px 14px; /* Slightly larger for readability */
        border-radius: 20px;
        font-size: 0.875rem; /* Adjusted for mobile */
        font-weight: 600;
    }
    .filter-pill {
        display: inline-flex;
        align-items: center;
        @apply bg-primary/10 text-primary;
        padding: 8px 14px; /* Larger for touch */
        border-radius: 20px;
        font-size: 0.875rem;
        margin-right: 8px;
        margin-bottom: 8px;
    }
    .color-indicator {
        display: inline-block;
        width: 14px; /* Slightly larger */
        height: 14px;
        border-radius: 50%;
        margin-right: 8px;
    }
    .table-container {
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
        max-width: 100%; /* Add this to constrain the container */
    }
    .table-container table {
        width: 100%;
        border-collapse: collapse;
    }
    .table-container th {
        position: sticky;
        top: 0;
        background: #f9fafb;
        z-index: 0;
        font-size: 0.75rem; /* Smaller for mobile */
        padding: 10px 12px;
    }
    .table-container td {
        padding: 12px;
        text-align: left;
        border-bottom: 1px solid #e5e7eb;
        font-size: 0.875rem; /* Adjusted for readability */
    }
    .table-container tr:hover {
        background-color: #f3f4f6;
    }

    /* Mobile-Specific Styles */
    @media (max-width: 767px) {
        .container {
            padding-left: 1rem;
            padding-right: 1rem;
        }
        /* Header */
        .bg-gradient-to-r.from-blue-600 {
            padding: 1rem; /* Reduced padding */
        }
        .bg-gradient-to-r.from-blue-600 h1 {
            font-size: 1.5rem; /* Smaller title */
        }
        .bg-gradient-to-r.from-blue-600 p {
            font-size: 0.875rem;
        }
        .bg-gradient-to-r.from-blue-600 a {
            padding: 0.75rem 1.5rem; /* Larger tap target */
            font-size: 0.875rem;
        }

        /* Statistics Cards */
        .stats-grid {
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .stats-grid > div {
            padding: 1rem;
        }
        .stats-grid p.text-2xl {
            font-size: 1.5rem; /* Smaller number */
        }
        .stats-grid p.text-sm {
            font-size: 0.875rem;
        }

        /* Filter Section */
        .md\:flex-row {
            flex-direction: column;
        }
        .md\:grid-cols-3 {
            grid-template-columns: 1fr; /* Stack filters */
        }
        .dropdown-btn {
            padding: 14px 16px; /* Larger tap target */
            font-size: 1rem;
        }
        .dropdown-item {
            padding: 14px 16px;
            font-size: 1rem;
        }
        .filter-pill {
            padding: 10px 16px; /* Larger tap target */
            font-size: 0.875rem;
        }
        #clear-filters {
            padding: 0.75rem 1.5rem; /* Larger tap target */
            font-size: 0.875rem;
        }

        /* Table/Card View */
        .table-container thead {
            display: none;
        }
        .table-container tr {
            display: block;
            margin-bottom: 1.5rem; /* More space between cards */
            border-radius: 0.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
            border: 1px solid #e5e7eb;
            overflow: hidden;
        }
        .table-container td {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 1rem; /* More padding */
            text-align: right;
            border-bottom: 1px solid #e5e7eb;
            font-size: 0.875rem; /* Larger text */
        }
        .table-container td::before {
            content: attr(data-label);
            font-weight: 600;
            text-align: left;
            margin-right: 1rem;
            font-size: 0.875rem; /* Larger label */
            flex: 1;
        }
        .table-container td img {
            width: 60px; /* Smaller image */
            height: 60px;
            border-radius: 0.5rem;
        }
        .table-container td .dropdown-btn {
            padding: 8px 12px; /* Smaller dropdowns in table */
            font-size: 0.875rem;
        }
        .table-container td .dropdown-item {
            padding: 10px 12px;
            font-size: 0.875rem;
        }
        .table-container td .dropdown-content {
            width: 100%;
            max-height: 200px; /* Smaller dropdown height */
        }
        .table-container td .fas {
            font-size: 1.25rem; /* Larger icons for actions */
        }
        .table-container td .flex.items-center {
            gap: 1.5rem; /* More space between action buttons */
        }

        /* Pagination */
        .mt-8 {
            padding: 0 1rem;
            text-align: center;
        }
        .mt-8 a, .mt-8 span {
            padding: 0.75rem 1rem; /* Larger tap targets */
            font-size: 0.875rem;
            margin: 0 0.25rem;
            border-radius: 0.5rem;
        }
    }

    /* Ensure dropdowns don't overflow on small screens */
    @media (max-width: 767px) {
        .dropdown-content {
            position: fixed;
            left: 1rem;
            right: 1rem;
            width: auto;
            max-width: calc(100% - 2rem);
        }
    }

    /* Modal Styles */
    #image-view-modal {
        transition: opacity 0.2s ease-in-out;
    }
    #image-view-modal.hidden {
        pointer-events: none;
    }
    #image-view-modal .modal-content {
        transition: transform 0.2s ease-in-out;
    }
    #image-view-modal.hidden .modal-content {
        transform: scale(0.95);    }

    /* Toast Notification */
    .toast-notification {
        transition: all 0.5s ease-in-out;
        /* animation: toast-in 0.5s, toast-out 0.5s 4.5s; */
    }
    @keyframes toast-in {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
    @keyframes toast-out {
        from { transform: translateX(0); opacity: 1; }
        to { transform: translateX(100%); opacity: 0; }
    }

</style>
<?php $__env->stopPush(); ?>

<?php $__env->startSection('content'); ?>
<div class="container mx-auto px-4 sm:px-6 lg:px-8 py-6">
    <div class="bg-white rounded-2xl shadow-lg overflow-hidden">
        <!-- Header -->
        <div class="bg-gradient-to-r from-primary to-indigo-700 px-4 sm:px-6 py-4">
            <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
                <div>
                    <h1 class="text-2xl sm:text-2xl font-bold text-white flex items-center"><i class="fas fa-boxes-stacked mr-3"></i>Product Information</h1>
                    <p class="text-blue-100 mt-1 text-sm sm:text-base">Click on dropdowns to change values or  new products.</p>
                </div>
                <div class="mt-4 md:mt-0">
                    <a href="<?php echo e(route('admin.products.create')); ?>" class="px-4 py-2 bg-primary text-white rounded-lg font-medium hover:bg-primary/90 transition-colors text-sm sm:text-base">
                        <i class="fas fa-plus mr-2"></i>Add Product
                    </a>
                </div>
            </div>
        </div>

        <!-- Statistics Cards -->
        <div class="px-4 sm:px-6 py-6 bg-gradient-to-r from-gray-50 to-blue-50 border-b border-gray-200">
            <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-6 gap-4 stats-grid">
                <div class="bg-white rounded-xl shadow p-4 text-center transition-transform hover:scale-105">
                    <p class="text-sm font-medium text-gray-500">Total Products</p>
                    <p class="text-xl sm:text-2xl font-bold text-gray-800" id="total-products"><?php echo e($stats['total_products']); ?></p>
                </div>
                <div class="bg-white rounded-xl shadow p-4 text-center transition-transform hover:scale-105">
                    <p class="text-sm font-medium text-gray-500">In Warehouse</p>
                    <p class="text-xl sm:text-2xl font-bold text-indigo-600" id="in-warehouse"><?php echo e($stats['in_warehouse']); ?></p>
                </div>
                <div class="bg-white rounded-xl shadow p-4 text-center transition-transform hover:scale-105">
                    <p class="text-sm font-medium text-gray-500">Shipped</p>
                    <p class="text-xl sm:text-2xl font-bold text-amber-500" id="shipped"><?php echo e($stats['shipped']); ?></p>
                </div>
                <div class="bg-white rounded-xl shadow p-4 text-center transition-transform hover:scale-105">
                    <p class="text-sm font-medium text-gray-500">Delivered</p>
                    <p class="text-xl sm:text-2xl font-bold text-green-600" id="delivered"><?php echo e($stats['delivered']); ?></p>
                </div>
                <div class="bg-white rounded-xl shadow p-4 text-center transition-transform hover:scale-105">
                    <p class="text-sm font-medium text-gray-500">Sold</p>
                    <p class="text-xl sm:text-2xl font-bold text-purple-600" id="sold"><?php echo e($stats['sold']); ?></p>
                </div>
                <div class="bg-white rounded-xl shadow p-4 text-center transition-transform hover:scale-105">
                    <p class="text-sm font-medium text-gray-500">Returned</p>
                    <p class="text-xl sm:text-2xl font-bold text-red-600" id="returned"><?php echo e($stats['returned']); ?></p>
                </div>
            </div>
        </div>

        <!-- Filter Section -->
        <div class="px-4 sm:px-6 py-6 border-b border-gray-200">
            <div class="flex flex-col md:flex-row md:items-center justify-between mb-6">
                <h2 class="text-lg sm:text-xl font-semibold text-gray-800 mb-2 md:mb-0">Filter Products</h2>
                <button id="clear-filters" class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors text-sm">
                    <i class="fas fa-times mr-1"></i> Clear All Filters
                </button>
            </div>

            <!-- Filter Grid -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <!-- Product Filter -->
                <div class="dropdown">
                    <div class="dropdown-btn" onclick="toggleDropdown('product-dropdown')">
                        <span class="flex items-center gap-2" id="product-filter-text">
                            <i class="fas fa-box text-gray-400"></i>
                            <span>Brands</span>
                        </span>
                        <i class="fas fa-chevron-down text-gray-400 transition-transform" id="product-chevron"></i>
                    </div>
                    <div id="product-dropdown" class="dropdown-content  p-8 text-start">
                        <div class="dropdown-item" onclick="selectFilter('product_name', 'all', 'All Products')">
                            <i class="fas fa-boxes-stacked text-gray-400 w-5"></i> All Brands
                        </div>
                        <?php $__currentLoopData = $productNames; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $brand => $models): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <div class="nested-dropdown">
                                <div class="dropdown-item justify-between" onclick="toggleNestedDropdown(event)">
                                    <span><?php echo e($brand); ?></span>
                                    <i class="fas fa-chevron-right text-xs transition-transform"></i>
                                </div>
                                <div class="nested-dropdown-content hidden bg-gray-50">
                                    <?php $__currentLoopData = $models; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $model): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <a class="dropdown-item" onclick="selectFilter('product_name', '<?php echo e(addslashes($model)); ?>', '<?php echo e(addslashes($model)); ?>')">
                                            <?php echo e($model); ?>

                                        </a>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </div>
                            </div>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </div>
                </div>

                <!-- Color Filter -->
                <div class="dropdown">
                    <div class="dropdown-btn" onclick="toggleDropdown('color-dropdown')">
                        <span class="flex items-center gap-2" id="color-filter-text">
                            <i class="fas fa-palette text-gray-400"></i>
                            <span>All Colors</span>
                        </span>
                        <i class="fas fa-chevron-down text-gray-400 transition-transform" id="color-chevron"></i>
                    </div>
                    <div id="color-dropdown" class="dropdown-content">
                        <div class="dropdown-item" onclick="selectFilter('color', 'all', 'All Colors')">
                            <i class="fas fa-paint-brush text-gray-400 w-5"></i> All Colors
                        </div>
                        <div class="nested-dropdown">
                            <div class="dropdown-item justify-between" onclick="toggleNestedDropdown(event)">
                                <span>Available Colors</span>
                                <i class="fas fa-chevron-right text-xs transition-transform"></i>
                            </div>
                            <div class="nested-dropdown-content hidden bg-gray-50 py-1">
                                <?php $__currentLoopData = $productColors; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $color): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <a class="dropdown-item" onclick="selectFilter('color', '<?php echo e($color); ?>', '<?php echo e($color); ?>')">
                                        <span class="color-indicator" style="background-color: <?php echo e(strtolower($color)); ?>; border: 1px solid #ccc;"></span> <?php echo e($color); ?>

                                    </a>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Status Filter -->
                <div class="dropdown">
                    <div class="dropdown-btn" onclick="toggleDropdown('status-dropdown')">
                        <span class="flex items-center gap-2" id="status-filter-text">
                            <i class="fas fa-truck-fast text-gray-400"></i>
                            <span>All Statuses</span>
                        </span>
                        <i class="fas fa-chevron-down text-gray-400 transition-transform" id="status-chevron"></i>
                    </div>
                    <div id="status-dropdown" class="dropdown-content">
                        <div class="dropdown-item" onclick="selectFilter('status', 'all', 'All Statuses')">
                            <i class="fas fa-circle-nodes text-gray-400 w-5"></i> All Statuses
                        </div>
                        <div class="nested-dropdown">
                            <div class="dropdown-item justify-between" onclick="toggleNestedDropdown(event)"><span>Inventory</span><i class="fas fa-chevron-right text-xs transition-transform"></i></div>
                            <div class="nested-dropdown-content hidden bg-gray-50 py-1">
                                <a class="dropdown-item" onclick="selectFilter('status', 'In Warehouse', 'In Warehouse')"><span class="status-badge bg-blue-100 text-blue-800">In Warehouse</span></a>
                            </div>
                        </div>
                        <div class="nested-dropdown">
                            <div class="dropdown-item justify-between" onclick="toggleNestedDropdown(event)"><span>In Transit</span><i class="fas fa-chevron-right text-xs transition-transform"></i></div>
                            <div class="nested-dropdown-content hidden bg-gray-50 py-1">
                                <a class="dropdown-item" onclick="selectFilter('status', 'Shipped', 'Shipped')"><span class="status-badge bg-amber-100 text-amber-800">Shipped</span></a>
                            </div>
                        </div>
                        <div class="nested-dropdown">
                            <div class="dropdown-item justify-between" onclick="toggleNestedDropdown(event)"><span>Completed</span><i class="fas fa-chevron-right text-xs transition-transform"></i></div>
                            <div class="nested-dropdown-content hidden bg-gray-50 py-1">
                                <a class="dropdown-item" onclick="selectFilter('status', 'Delivered', 'Delivered')"><span class="status-badge bg-green-100 text-green-800">Delivered</span></a>
                                <a class="dropdown-item" onclick="selectFilter('status', 'Sold', 'Sold')"><span class="status-badge bg-purple-100 text-purple-800">Sold</span></a>
                            </div>
                        </div>
                        <div class="nested-dropdown">
                            <div class="dropdown-item justify-between" onclick="toggleNestedDropdown(event)"><span>Issues</span><i class="fas fa-chevron-right text-xs transition-transform"></i></div>
                            <div class="nested-dropdown-content hidden bg-gray-50 py-1">
                                <a class="dropdown-item" onclick="selectFilter('status', 'Returned', 'Returned')"><span class="status-badge bg-red-100 text-red-800">Returned</span></a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Active Filters -->
            <div id="active-filters" class="mt-6 hidden">
                <h3 class="text-sm font-medium text-gray-500 mb-2">Active Filters:</h3>
                <div id="filter-pills" class="flex flex-wrap"></div>
            </div>
        </div>

        <!-- Products Table -->
        <div class="p-4 sm:p-6">
            <div class="table-container overflow-x-auto">
                <table>
                    <thead>
                        <tr class="text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            <th><i class="fas fa-image mr-1 hidden sm:inline"></i>Image</th>
                            <th><i class="fas fa-copyright mr-1 hidden sm:inline"></i>Brand</th>
                            <th><i class="fas fa-box mr-1 hidden sm:inline"></i>Model</th>
                            <th><i class="fas fa-palette mr-1 hidden sm:inline"></i>Color</th>
                            <th class="text-right"><i class="fas fa-dollar-sign mr-1 hidden sm:inline"></i>PP</th>
                            <th class="text-right"><i class="fas fa-dollar-sign mr-1 hidden sm:inline"></i>RP</th>
                            <th class="text-right"><i class="fas fa-dollar-sign mr-1 hidden sm:inline"></i>DP</th>
                            <th class="text-right"><i class="fas fa-dollar-sign mr-1 hidden sm:inline"></i>MRP</th>
                            <th class="text-right"><i class="fas fa-dollar-sign mr-1 hidden sm:inline"></i>DP</th>
                            <th><i class="fas fa-warehouse ml-2 hidden sm:inline"></i>Stock</th>
                            <th><i class="fas fa-cogs mr-1 hidden sm:inline"></i>Actions</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200" id="product-table-body">
                        <?php $__empty_1 = true; $__currentLoopData = $products; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $product): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                            <?php
                                // Extract brand and model from product_name
                                $nameParts = explode(' ', $product->product_name, 2);
                                $brand = $nameParts[0];
                                $model = $nameParts[1] ?? '';
                            ?>
                            <?php
                                // The 'gallery_images' attribute is already cast to an array by the model.
                                $galleryImages = $product->gallery_images ?? [];

                                // Determine the primary image
                                $primaryImage = !empty($galleryImages) && isset($galleryImages[0]['image']) ? $galleryImages[0]['image'] : $product->image;
                            ?>
                            <tr data-product-id="<?php echo e($product->id); ?>" class="hover:bg-gray-50 transition-colors">
                                <td data-label="Image">
                                    <img src="<?php echo e($primaryImage ? asset('storage/' . $primaryImage) : 'https://via.placeholder.com/150'); ?>"
                                         alt="<?php echo e($product->product_name); ?>"
                                         class="h-12 w-12 object-cover rounded-md cursor-pointer"
                                         onclick="openImageViewModal('<?php echo e($primaryImage ? asset('storage/' . $primaryImage) : 'https://via.placeholder.com/150'); ?>', '<?php echo e(e($product->product_name)); ?>')">
                                </td>
                                <td data-label="Brand" class="font-medium text-gray-900"><?php echo e($brand); ?></td>
                                <td data-label="Model"><?php echo e($model); ?></td>
                                <td data-label="Color">
                                    <?php
                                        // Ensure $colors is always an array for consistent handling
                                        $colors = is_array($product->color) ? $product->color : (is_string($product->color) ? json_decode($product->color, true) : [$product->color]);
                                        if (!is_array($colors)) $colors = [$colors]; // Fallback for non-JSON strings or other types
                                    ?>
                                    <div class="flex items-center gap-1">
                                        <?php $__currentLoopData = $colors; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $color): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <span class="h-4 w-4 rounded-full border" style="background-color: <?php echo e(strtolower(is_string($color) ? $color : '')); ?>;" title="<?php echo e(is_string($color) ? $color : ''); ?>"></span>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </div>
                                </td>
                                <td data-label="Purchase Price" class="text-right">৳<?php echo e(number_format($product->cost, 2)); ?></td>
                                <td data-label="Retail Price" class="text-right">৳<?php echo e(number_format($product->retail_price, 2)); ?></td>
                                <td data-label="Discount Price" class="text-right text-red-600 font-semibold">৳<?php echo e(number_format($product->discount_price, 2)); ?></td>
                                <td data-label="MRP" class="text-right">৳<?php echo e(number_format($product->price, 2)); ?></td>
                                <td data-label="Dealer Price" class="text-right font-semibold text-green-700">৳<?php echo e(number_format($product->dealer_price, 2)); ?></td>
                                <td data-label="Stock">
                                    <div class="dropdown">
                                        <div class="dropdown-btn" onclick="toggleDropdown('status-dropdown-<?php echo e($product->id); ?>', event)">
                                            <span id="status-badge-<?php echo e($product->id); ?>" class="status-badge <?php echo e(match($product->status) {
                                                    'In Warehouse' => 'bg-blue-100 text-blue-800',
                                                    'Shipped' => 'bg-amber-100 text-amber-800',
                                                    'Delivered' => 'bg-green-100 text-green-800',
                                                    'Sold' => 'bg-purple-100 text-purple-800',
                                                    'Returned' => 'bg-red-100 text-red-800',
                                                    default => 'bg-gray-100 text-gray-800'
                                                }); ?>"><?php echo e($product->status); ?></span>
                                            <i class="fas fa-chevron-down text-gray-400 text-xs transition-transform"></i>
                                        </div>
                                        <div id="status-dropdown-<?php echo e($product->id); ?>" class="dropdown-content">
                                            <a class="dropdown-item" onclick="updateProductField('<?php echo e($product->id); ?>', 'status', 'In Warehouse')">In Warehouse</a>
                                            <a class="dropdown-item" onclick="updateProductField('<?php echo e($product->id); ?>', 'status', 'Shipped')">Shipped</a>
                                            <a class="dropdown-item" onclick="updateProductField('<?php echo e($product->id); ?>', 'status', 'Delivered')">Delivered</a>
                                            <a class="dropdown-item" onclick="updateProductField('<?php echo e($product->id); ?>', 'status', 'Sold')">Sold</a>
                                            <a class="dropdown-item" onclick="updateProductField('<?php echo e($product->id); ?>', 'status', 'Returned')">Returned</a>
                                        </div>
                                    </div>
                                </td>
                                <td data-label="Actions">
                                    <div class="flex items-center justify-end gap-4 text-gray-500">
                                        <a href="<?php echo e(route('admin.stock.edit', $product->id)); ?>" class="hover:text-primary transition-colors" title="Edit Stock Details">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                    <a href="<?php echo e(route('sticker.print', ['serial_no' => $product->serial_no])); ?>" target="_blank" class="hover:text-primary transition-colors" title="Print Sticker">
                                            <i class="fas fa-qrcode"></i>
                                        </a>
                                        <form action="<?php echo e(route('admin.products.delete', $product->id)); ?>" method="POST" onsubmit="return confirm('Are you sure you want to delete this product?');" class="inline">
                                            <?php echo csrf_field(); ?>
                                            <?php echo method_field('DELETE'); ?>
                                            <button type="submit" class="hover:text-red-600 transition-colors" title="Delete Product">
                                                <i class="fas fa-trash-alt"></i>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                            <tr>
                                <td colspan="11" class="text-center py-12">
                                    <div class="flex flex-col items-center justify-center text-gray-500">
                                        <i class="fas fa-box-open fa-3x mb-4"></i>
                                        <h3 class="text-xl font-semibold mb-2">No Products Found</h3>
                                        <p class="text-sm">Your search or filter criteria did not match any products.</p>
                                        <a href="<?php echo e(route('admin.stock.index')); ?>" class="mt-4 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">
                                            Clear Filters
                                        </a>
                                    </div>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            <!-- Pagination Container -->
            <div id="pagination-container" class="mt-8">
                <?php echo $products->links('vendor.pagination.tailwind'); ?>

            </div>
        </div>
        </div>
    </div>

    <!-- Image View Modal -->
    <div id="image-view-modal" class="fixed inset-0 bg-black bg-opacity-75 z-50 hidden flex items-center justify-center p-4 opacity-0" onclick="closeImageModal()">
        <div class="modal-content bg-white rounded-lg shadow-xl max-w-lg w-full relative transform" onclick="event.stopPropagation()">
            <!-- Close button for better mobile experience -->
            <button onclick="closeImageModal()" class="absolute top-2 right-2 bg-gray-800 bg-opacity-50 text-white rounded-full h-8 w-8 flex items-center justify-center text-lg font-bold hover:bg-opacity-75 transition-colors z-10" aria-label="Close image viewer">&times;</button>

            <img id="modal-image" src="" alt="Product Image Full View" class="w-full h-auto object-contain rounded-t-lg max-h-[70vh]">
            <div class="p-4 border-t">
                <h3 id="modal-product-name" class="text-lg font-semibold text-gray-800 text-center"></h3>
            </div>
        </div>
    </div>

    <!-- Image Edit Modal -->
    
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
    document.addEventListener('DOMContentLoaded', function() {

        // Check for session flash messages and show toast
        <?php if(session('success')): ?>
            showToast('<?php echo e(session('success')); ?>', 'success');
        <?php endif; ?>
        <?php if(session('error')): ?>
            showToast('<?php echo e(session('error')); ?>', 'error');
        <?php endif; ?>

        const allProductNames = <?php echo json_encode($productNames, 15, 512) ?>;
        const allProductColors = <?php echo json_encode($productColors, 15, 512) ?>;
        const clearFiltersBtn = document.getElementById('clear-filters');
        const activeFiltersContainer = document.getElementById('active-filters');
        const filterPillsContainer = document.getElementById('filter-pills');
        const urlParams = new URLSearchParams(window.location.search);
        const productTableBody = document.getElementById('product-table-body');
        const paginationContainer = document.getElementById('pagination-container');

        // populateFilterDropdowns(); // This is now handled by Blade
        updateActiveFilters();

        clearFiltersBtn.addEventListener('click', clearFilters);

        // document.addEventListener('click', function(event) {
        //     if (!event.target.closest('.dropdown')) {
        //         closeAllDropdowns();
        //     }
        // });

        // Initial pagination listener setup
        setupPaginationListeners();

        // Event delegation for opening the image edit modal
        productTableBody.addEventListener('click', function(event) {
            const target = event.target.closest('button[data-action="open-image-edit-modal"]');
            if (target) {
                // This button is inside the product_table_body partial
                event.preventDefault();
                const productId = target.dataset.productId;
                const imageUrl = target.dataset.imageUrl;
                openImageEditModal(productId, imageUrl);
            }
        });

        function setupPaginationListeners() {
            paginationContainer.addEventListener('click', handlePaginationClick);
        }

        function getStatusBadgeClass(status) {
            const classes = {
                "In Warehouse": "bg-blue-100 text-blue-800",
                "Shipped": "bg-amber-100 text-amber-800",
                "Delivered": "bg-green-100 text-green-800", // Corrected class
                "Sold": "bg-purple-100 text-purple-800",
                "Returned": "bg-red-100 text-red-800"
            };
            return classes[status] || 'bg-gray-100 text-gray-800';
        }

        function getColorClass(colorName) {
            const color = colorName.toLowerCase();
            const classes = {
                'white': 'bg-white border',
                'black': 'bg-black',
                'cyan': 'bg-cyan-500',
                'red': 'bg-red-500',
                'blue': 'bg-blue-500',
                'green': 'bg-green-500',
                'amber': 'bg-amber-500',
                'purple': 'bg-purple-500'
            };
            return classes[color] || 'bg-gray-300 border';
        }


        window.toggleDropdown = function(dropdownId, event) {
            const dropdown = document.getElementById(dropdownId);
            const isShowing = dropdown.classList.contains('show');

            closeAllDropdowns();

            if (!isShowing) {
                if (dropdown) dropdown.classList.add('show');
                const chevron = dropdown.previousElementSibling.querySelector('i.fa-chevron-down');
                if (chevron) {
                    chevron.style.transform = 'rotate(180deg)';
                }
            }
            if (event) {
                event.stopPropagation();
            }
        }

        function closeAllDropdowns() {
            document.querySelectorAll('.dropdown-content').forEach(dropdown => {
                dropdown.classList.remove('show');
            });
            document.querySelectorAll('.dropdown-btn i').forEach(chevron => {
                chevron.style.transform = 'rotate(0deg)';
            });
        }

        window.toggleNestedDropdown = function(event) {
            event.stopPropagation(); // Prevent the main dropdown from closing
            const parent = event.currentTarget.parentElement;
            const content = parent.querySelector('.nested-dropdown-content');
            const icon = parent.querySelector('.fa-chevron-right');

            content.classList.toggle('hidden');
            icon.classList.toggle('rotate-90');

            // Close other open nested dropdowns
            document.querySelectorAll('.nested-dropdown-content').forEach(c => { if (c !== content) { c.classList.add('hidden'); c.previousElementSibling.querySelector('.fa-chevron-right').classList.remove('rotate-90'); }});
        }

        window.selectFilter = function(type, value, displayText) {
            const currentUrl = new URL(window.location.href);
            if (value === 'all') {
                currentUrl.searchParams.delete(type);
            } else {
                currentUrl.searchParams.set(type, value);
            }
            currentUrl.searchParams.set('page', 1); // Reset to first page on filter change
            applyFilters(currentUrl.searchParams.toString());
        };

        function clearFilters() {
            window.location.href = window.location.pathname;
        }

        function updateActiveFilters() {
            filterPillsContainer.innerHTML = '';
            let hasActiveFilters = false;

            const currentProduct = urlParams.get('product_name');
            const currentColor = urlParams.get('color');
            const currentStatus = urlParams.get('status');

            if (currentProduct && currentProduct !== 'all') {
                document.getElementById('product-filter-text').innerHTML = `<i class="fas fa-box text-gray-400"></i><span>${currentProduct}</span>`;
                addPill('product_name', currentProduct);
                hasActiveFilters = true;
            }
            if (currentColor && currentColor !== 'all') {
                document.getElementById('color-filter-text').innerHTML = `
                    <i class="fas fa-palette text-gray-400"></i>
                    <span class="flex items-center gap-2">
                        <span class="color-indicator ${getColorClass(currentColor)}"></span>
                        ${currentColor}
                    </span>`;
                addPill('color', currentColor);
                hasActiveFilters = true;
            }
            if (currentStatus && currentStatus !== 'all') {
                document.getElementById('status-filter-text').innerHTML = `<i class="fas fa-truck-fast text-gray-400"></i><span class="status-badge ${getStatusBadgeClass(currentStatus)}">${currentStatus}</span>`;
                addPill('status', currentStatus);
                hasActiveFilters = true;
            }

            function addPill(type, value) {
                const filterPill = document.createElement('div');
                filterPill.className = 'filter-pill';
                let content = value;
                if (type === 'color') {
                    content = `<span class="flex items-center gap-2"><span class="color-indicator ${getColorClass(value)}"></span> ${value}</span>`;
                }
                filterPill.innerHTML = `${content} <i class="fas fa-times ml-2 cursor-pointer" onclick="removeFilter('${type}')"></i>`;
                filterPillsContainer.appendChild(filterPill);
            }

            activeFiltersContainer.classList.toggle('hidden', !hasActiveFilters);
        }

        window.removeFilter = function(type) {
            const currentUrl = new URL(window.location.href);
            currentUrl.searchParams.delete(type);
            currentUrl.searchParams.set('page', 1); // Reset to first page
            applyFilters(currentUrl.searchParams.toString());
        };

        window.updateProductField = function(productId, field, value) {
            const formData = new FormData();
            formData.append(field, value);
            formData.append('_method', 'PUT');

            fetch(`/admin/products/${productId}`, {
                method: 'POST', // Use POST for FormData with method spoofing
                headers: {
                    'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>',
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast(data.message, 'success');
                    const row = document.querySelector(`tr[data-product-id='${productId}']`);
                    if (row) {
                        // Update the text in the dropdown button
                        if (field === 'status') {
                            const btnSpan = row.querySelector(`#status-badge-${productId}`);
                            if (btnSpan) {
                                btnSpan.textContent = value;
                                btnSpan.className = `status-badge ${getStatusBadgeClass(value)}`;
                            }
                        }
                    }
                    // Update stats
                    if (data.stats) { // This block will now execute
                        updateStats(data.stats);
                    }
                } else {
                    showToast(data.message || 'Update failed!', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('An unexpected error occurred.', 'error');
            })
            .finally(() => {
                closeAllDropdowns();
            });
        };

        function applyFilters(queryString) {
            const url = `<?php echo e(route('admin.stock.index')); ?>?${queryString}`;
            history.pushState(null, '', url);

            // Add a loading indicator
            productTableBody.style.opacity = '0.5';

            fetch(url, {
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json',
                }
            })
            .then(response => response.json())
            .then(data => {
                productTableBody.innerHTML = data.table_html;
                updateStats(data.stats);
                paginationContainer.innerHTML = data.pagination_html;
                setupPaginationListeners(); // Re-attach listeners to new pagination links
                updateActiveFilters(); // Re-run to update pills
            })
            .catch(error => {
                console.error('Filter error:', error);
                showToast('Failed to apply filters.', 'error');
            })
            .finally(() => {
                productTableBody.style.opacity = '1';
            });
        }

        function openImageEditModal(productId, currentImageUrl) {
            const modal = document.getElementById('image-edit-modal');
            if (!modal) return;

            const form = document.getElementById('image-edit-form');
            const imageInput = document.getElementById('edit_image_input');
            const errors = document.getElementById('image-modal-errors');

            if (form) form.reset(); // Reset form fields, but not the image src yet
            document.getElementById('edit_image_product_id').value = productId;
            document.getElementById('edit_image_preview').src = currentImageUrl;
            if (imageInput) imageInput.value = ''; // Specifically clear the file input
            if (errors) errors.classList.add('hidden');
            modal.classList.remove('hidden');
        }


        function handlePaginationClick(event) {
            const link = event.target.closest('a');
            if (link && link.href && !link.href.endsWith('#')) {
                event.preventDefault();
                fetchPage(link.href);
            }
        }

        function fetchPage(url) {
            productTableBody.style.opacity = '0.5';

            fetch(url, {
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json',
                }
            })
            .then(response => response.json())
            .then(data => {
                productTableBody.innerHTML = data.table_html;
                paginationContainer.innerHTML = data.pagination_html;
                setupPaginationListeners(); // Re-attach listeners

                // Scroll to the top of the table for better UX
                const tableContainer = document.querySelector('.table-container');
                if (tableContainer) {
                    tableContainer.scrollIntoView({ behavior: 'smooth' });
                }
            })
            .catch(error => {
                console.error('Pagination error:', error);
                showToast('Failed to load page.', 'error');
            })
            .finally(() => {
                productTableBody.style.opacity = '1';
            });
        }

        function updateStats(stats) {
            document.getElementById('total-products').textContent = stats.total_products;
            document.getElementById('in-warehouse').textContent = stats.in_warehouse;
            document.getElementById('shipped').textContent = stats.shipped;
            document.getElementById('delivered').textContent = stats.delivered;
            document.getElementById('sold').textContent = stats.sold;
            document.getElementById('returned').textContent = stats.returned;
        }

        window.openImageViewModal = function(imageUrl, productName) {
            const modal = document.getElementById('image-view-modal');
            const modalImage = document.getElementById('modal-image');
            const modalProductName = document.getElementById('modal-product-name');

            if (modal && modalImage && modalProductName) {
                modalImage.src = imageUrl;
                modalProductName.textContent = productName;
                modal.classList.remove('opacity-0');
                modal.classList.remove('hidden');
                document.body.style.overflow = 'hidden'; // Prevent background scrolling
            }
        }

        window.closeImageModal = function() {
            const modal = document.getElementById('image-view-modal');
            if (modal) {
                modal.classList.add('opacity-0');
                setTimeout(() => {
                    modal.classList.add('hidden');
                    document.body.style.overflow = 'auto'; // Restore scrolling
                }, 200); // Match the transition duration
            }
        }

        // Image Edit Modal Logic
        const imageEditModal = document.getElementById('image-edit-modal');
        const closeImageModalBtn = document.getElementById('close-image-modal-btn');
        const cancelImageModalBtn = document.getElementById('cancel-image-modal-btn');
        const imageEditForm = document.getElementById('image-edit-form');
        const imageInput = document.getElementById('edit_image_input');
        const imagePreview = document.getElementById('edit_image_preview');

        function closeImageEditModal() {
            if (imageEditModal) {
                imageEditModal.classList.add('hidden');
            }
        }

        if (closeImageModalBtn) closeImageModalBtn.addEventListener('click', closeImageEditModal);
        if (cancelImageModalBtn) cancelImageModalBtn.addEventListener('click', closeImageEditModal);

        if (imageInput) {
            imageInput.addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(event) {
                        imagePreview.src = event.target.result;
                    }
                    reader.readAsDataURL(file);
                }
            });
        }

        if (imageEditForm) {
            imageEditForm.addEventListener('submit', function(e) {
                e.preventDefault();
                const productId = document.getElementById('edit_image_product_id').value;
                const imageFile = document.getElementById('edit_image_input').files[0];

                const formData = new FormData();
                formData.append('image', imageFile);
                formData.append('product_id', productId);
                formData.append('_method', 'PUT');

                fetch(`/admin/products/${productId}`, {
                    method: 'POST', // FormData with files requires POST
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                        'X-Requested-With': 'XMLHttpRequest',
                        'Accept': 'application/json',
                    },
                    body: formData
                })
                .then(response => {
                    // Check if the response is successful (2xx) or a validation error (422)
                    if (response.ok || response.status === 422) {
                        return response.json();
                    }
                    // For other errors, throw an error to be caught by .catch()
                    return response.text().then(text => { throw new Error(text || 'Server error') });
                })
                .then(data => {
                    const errorContainer = document.getElementById('image-modal-errors');
                    if (data.errors) { // This is a validation error response
                        let errorHtml = '<p class="font-bold">Error:</p><ul>';
                        for (const field in data.errors) {
                            errorHtml += `<li>${data.errors[field][0]}</li>`;
                        }
                        errorHtml += '</ul>';
                        errorContainer.innerHTML = errorHtml;
                        errorContainer.classList.remove('hidden');
                        showToast(data.message || 'Please correct the errors.', 'error');
                    } else if (data.success) { // This is a success response
                        showToast('Image updated successfully!', 'success');
                        closeImageEditModal();
                        // Update the image in the table without a full reload
                        const productRow = document.querySelector(`tr[data-product-id='${productId}']`);
                        if (productRow) {
                            const tableImg = productRow.querySelector('img');
                            const editBtn = productRow.querySelector('button[data-action="open-image-edit-modal"]');
                            const newImageUrl = data.product.image_url;
                            // Apply cache-busting query string to force browser to reload the image
                            const newImageUrlWithCacheBust = newImageUrl + '?' + new Date().getTime();
                            if (tableImg) {
                                tableImg.src = newImageUrlWithCacheBust;
                                const newProductName = data.product.product_name;
                                tableImg.setAttribute('onclick', `openImageViewModal('${newImageUrlWithCacheBust}', '${newProductName.replace(/'/g, "\\'")}')`); // Update modal call
                            }
                            if (editBtn) editBtn.dataset.imageUrl = newImageUrl; // Update button data attribute
                        }
                    }
                })
                .catch(error => {
                    console.error('Fetch Error:', error);
                    showToast('An unexpected error occurred during upload.', 'error');
                });
            });
        }

        // Enhanced Notification function from scanner page
        function showToast(message, type = 'info') {
            // Remove any existing notifications
            document.querySelectorAll('.toast-notification').forEach(n => n.remove());

            const notification = document.createElement('div');
            notification.className = 'toast-notification fixed top-5 right-5 w-full max-w-sm bg-white shadow-2xl rounded-xl p-4 border-l-4 z-[1000]';

            const icons = { success: 'fa-check-circle', error: 'fa-exclamation-circle', info: 'fa-info-circle' };
            const borderColors = { success: 'border-green-500', error: 'border-red-500', info: 'border-blue-500' };
            const textColors = { success: 'text-green-500', error: 'text-red-500', info: 'text-blue-500' };

            notification.classList.add(borderColors[type] || borderColors.info);

            notification.innerHTML = `
                <div class="flex items-start gap-4">
                    <i class="fas ${icons[type] || icons.info} ${textColors[type] || textColors.info} text-2xl mt-1"></i>
                    <div class="flex-1">
                        <p class="font-bold text-gray-800">${type.charAt(0).toUpperCase() + type.slice(1)}</p>
                        <p class="text-sm text-gray-600">${message}</p>
                    </div>
                    <button class="v-alert-close text-gray-400 hover:text-gray-600" onclick="this.closest('.toast-notification').remove()">&times;</button>
                </div>
                <div class="absolute bottom-0 left-0 h-1 bg-gray-200 rounded-bl-lg">
                    <div class="h-1 ${borderColors[type] ? borderColors[type].replace('border', 'bg') : 'bg-blue-500'} rounded-bl-lg" style="width: 100%; animation: progress 4s linear forwards;"></div>
                </div>
            `;

            document.body.appendChild(notification);
            notification.style.animation = 'toast-in 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94) forwards';

            const close = () => {
                notification.style.animation = 'toast-out 0.5s ease-in forwards';
                notification.addEventListener('animationend', () => notification.remove(), { once: true });
            };

            setTimeout(close, 4000);
        }
    });
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp\htdocs\E-Product-Verify-Auth-Application-5\resources\views\admin\index.blade.php ENDPATH**/ ?>