<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            قدم ۴: انتخاب محصولات
        </h2>
        <p class="text-sm text-gray-600 mt-1">
            شما در حال ثبت سفارش برای طرح
            <span class="font-semibold text-indigo-600">{{ $planOptionDetails['name'] }}</span>
            ( {{ $planOptionDetails['months'] }} ماهه / ضریب: {{ $planOptionDetails['coefficient'] }}% )
            هستید.
        </p>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8 grid grid-cols-1 lg:grid-cols-3 gap-6">

            <div class="lg:col-span-2 space-y-6">
                
                <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                    <div class="p-6 bg-white border-b border-gray-200">
                        <form action="{{ route('agent.cart.products') }}" method="GET">
                            <div class="flex space-x-2 space-x-reverse">
                                <x-text-input id="search" name="search" type="text" class="block w-full" :value="request('search')" placeholder="جستجو در نام یا کد محصول/باندل..." />
                                <x-primary-button>
                                    جستجو
                                </x-primary-button>
                            </div>
                        </form>
                    </div>
                </div>

                {{-- =================================== --}}
                {{-- بخش محصولات (نمای جدولی) --}}
                {{-- =================================== --}}
                <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                    <div class="text-gray-900">
                        <h3 class="text-lg font-semibold mb-4 p-6 border-b">محصولات مجاز برای این طرح</h3>
                        
                        <div class="overflow-x-auto">
                            <table class="min-w-full divide-y divide-gray-200">
                                <thead class="bg-gray-50">
                                    <tr>
                                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">تصویر</th>
                                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">عنوان</th>
                                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">قیمت (ریال)</th>
                                        <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase">موجودی</th>
                                        <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase">عملیات</th>
                                    </tr>
                                </thead>
                                <tbody class="bg-white divide-y divide-gray-200">
                                    @forelse($products as $product)
                                        @php
                                            $hasDiscount = $product->discount_price > 0 && $product->discount_price < $product->price;
                                            $displayPrice = $product->active_price;
                                            $isInCart = isset($cart['items']['product_'.$product->id]);
                                            $buttonText = $isInCart ? 'به‌روزرسانی' : 'افزودن';
                                            $isOutOfStock = $product->stock <= 0;
                                            $quantityInCart = $cart['items']['product_'.$product->id]['quantity'] ?? 1;
                                        @endphp

                                        <tr @class(['bg-gray-50' => $loop->even])>
                                            <td class="p-4">
                                                <img src="{{ $product->image_path ? asset('storage/' . $product->image_path) : 'https://via.placeholder.com/80' }}" 
                                                     alt="{{ $product->name }}" 
                                                     class="w-16 h-16 object-cover rounded">
                                            </td>
                                            <td class="p-4">
                                                <a href="{{ route('agent.products.show', $product) }}" target="_blank" class="font-medium text-indigo-600 hover:text-indigo-800" title="مشاهده جزئیات">
                                                    {{ $product->name }}
                                                </a>
                                                <div class="text-sm text-gray-500">{{ $product->code }}</div>
                                            </td>
                                            <td class="p-4">
                                                @if($hasDiscount)
                                                    <span class="font-bold text-red-600">{{ number_format($displayPrice) }}</span>
                                                    <span class="text-sm text-gray-500 line-through ml-1">{{ number_format($product->price) }}</span>
                                                @else
                                                    <span class="font-bold text-gray-800">{{ number_format($displayPrice) }}</span>
                                                @endif
                                            </td>
                                            <td class="p-4 text-center">
                                                <span class="text-sm font-bold {{ $product->stock > 0 ? 'text-green-600' : 'text-red-600' }}">
                                                    {{ $product->stock }}
                                                </span>
                                            </td>
                                            <td class="p-4">
                                                <form action="{{ route('agent.cart.add') }}" method="POST">
                                                    @csrf
                                                    <input type="hidden" name="item_id" value="{{ $product->id }}">
                                                    <input type="hidden" name="item_type" value="product">
                                                    <div class="flex flex-col gap-2 items-center" style="width: 120px;">
                                                        @if($isOutOfStock)
                                                            <x-text-input type="number" name="quantity" value="0" class="w-20 text-center" disabled />
                                                            <x-primary-button class="w-full justify-center opacity-50 cursor-not-allowed" disabled>
                                                                ناموجود
                                                            </x-primary-button>
                                                        @else
                                                            <x-text-input 
                                                                type="number" 
                                                                name="quantity" 
                                                                value="{{ $quantityInCart }}" 
                                                                min="1" 
                                                                max="{{ $product->stock }}" 
                                                                class="w-20 text-center" 
                                                            />
                                                            <x-primary-button class="w-full justify-center">
                                                                {{ $buttonText }}
                                                            </x-primary-button>
                                                        @endif
                                                    </div>
                                                </form>
                                            </td>
                                        </tr>
                                    @empty
                                        <tr>
                                            <td colspan="5" class="text-center py-6 text-gray-500">محصولی (بر اساس فیلترها) برای این طرح یافت نشد.</td>
                                        </tr>
                                    @endforelse
                                </tbody>
                            </table>
                        </div>
                        
                        <div class="mt-6 p-4 border-t">
                            {{-- اصلاحیه pagination --}}
                            {{ $products->appends(['bundles_page' => $bundles->currentPage(), 'search' => request('search')])->links() }}
                        </div>
                    </div>
                </div>

                {{-- =================================== --}}
                {{-- ✅✅✅ بخش باندل‌ها (بازگردانی شده) ✅✅✅ --}}
                {{-- =================================== --}}
                <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                    <div class="p-6 bg-white border-b border-gray-200">
                        <h3 class="text-lg font-semibold mb-4">باندل‌های پیشنهادی</h3>
                        
                        <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
                            @forelse($bundles as $bundle)
                                @php
                                    $bundle_has_stock = true;
                                    foreach ($bundle->products as $productInBundle) {
                                        if ($productInBundle->stock < $productInBundle->pivot->quantity) {
                                            $bundle_has_stock = false;
                                            break;
                                        }
                                    }
                                    $isBundleInCart = isset($cart['items']['bundle_'.$bundle->id]);
                                    $bundleButtonText = $isBundleInCart ? 'به‌روزرسانی' : 'افزودن';
                                    $bundleQuantityInCart = $cart['items']['bundle_'.$bundle->id]['quantity'] ?? 1;
                                @endphp

                                <div class="border rounded-lg shadow-sm flex flex-col justify-between">
                                    <div class="p-4">
                                        <h3 class="text-lg font-semibold text-gray-800">{{ $bundle->name }}</h3>
                                        <ul class="text-sm text-gray-600 mt-2 list-disc list-inside">
                                            @foreach($bundle->products as $productInBundle)
                                                <li>{{ $productInBundle->name }} ({{ $productInBundle->pivot->quantity }} عدد)</li>
                                            @endforeach
                                        </ul>

                                        <div class="mt-2">
                                            <span class="text-xl font-bold text-gray-800">{{ number_format($bundle->price) }}</span>
                                            <span class="text-sm text-gray-700">ریال</span>
                                        </div>
                                        <p class="text-sm mt-1 {{ $bundle_has_stock ? 'text-green-600' : 'text-red-600' }}">
                                            {{ $bundle_has_stock ? 'موجود' : 'ناموجود' }}
                                        </p>
                                    </div>
                                    
                                    <div class="p-4 bg-gray-50 rounded-b-lg">
                                        <form action="{{ route('agent.cart.add') }}" method="POST">
                                            @csrf
                                            <input type="hidden" name="item_id" value="{{ $bundle->id }}">
                                            <input type="hidden" name="item_type" value="bundle">
                                            <div class="flex space-x-2 space-x-reverse">
                                                {{-- اصلاحیه خطای endif --}}
                                                @if(!$bundle_has_stock)
                                                    <x-text-input 
                                                        type="number" 
                                                        name="quantity" 
                                                        value="{{ $bundleQuantityInCart }}" 
                                                        min="1" 
                                                        class="w-20 text-center" 
                                                        disabled
                                                    />
                                                    <x-primary-button class="flex-1 opacity-50 cursor-not-allowed" disabled>
                                                        {{ $bundleButtonText }}
                                                    </x-primary-button>
                                                @else
                                                    <x-text-input 
                                                        type="number" 
                                                        name="quantity" 
                                                        value="{{ $bundleQuantityInCart }}" 
                                                        min="1" 
                                                        class="w-20 text-center" 
                                                    />
                                                    <x-primary-button class="flex-1">
                                                        {{ $bundleButtonText }}
                                                    </x-primary-button>
                                                @endif
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            @empty
                                <p class="md:col-span-2 xl:col-span-3 text-center text-gray-500">باندلی (بر اساس فیلترها) یافت نشد.</p>
                            @endforelse
                        </div>
                        
                        <div class="mt-6">
                             {{-- اصلاحیه pagination --}}
                            {{ $bundles->appends(['products_page' => $products->currentPage(), 'search' => request('search')])->links() }}
                        </div>
                    </div>
                </div>

            </div>

            {{-- (بخش سبد خرید - بدون تغییر) --}}
            <div class="lg:col-span-1">
                <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg sticky top-8">
                    <div class="p-6 bg-white border-b border-gray-200">
                        <h3 class="text-lg font-semibold mb-4">سبد خرید شما</h3>

                        @if(session('success'))
                            <div class="mb-4 bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative" role="alert">
                                {{ session('success') }}
                            </div>
                        @endif
                        @if(session('error'))
                            <div class="mb-4 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert">
                                {{ session('error') }}
                            </div>
                        @endif

                        <div class="space-y-4">
                            @forelse($cart['items'] as $cartItemId => $item)
                                <div class="flex justify-between items-center border-b pb-2">
                                    <div>
                                        <p class="font-semibold">{{ $item['name'] }}</p>
                                        <p class="text-sm text-gray-600">
                                            {{ $item['quantity'] }} عدد × {{ number_format($item['price']) }} ریال
                                        </p>
                                    </div>
                                    <form action="{{ route('agent.cart.remove') }}" method="POST">
                                        @csrf
                                        <input type="hidden" name="cart_item_id" value="{{ $cartItemId }}">
                                        <x-danger-button class="text-xs px-2 py-1">حذف</x-danger-button>
                                    </form>
                                </div>
                            @empty
                                <p class="text-gray-500 text-center">سبد خرید خالی است.</p>
                            @endforelse
                        </div>

                        @if(!empty($cart['items']))
                            <div class="mt-6 pt-4 border-t">
                                <div class="flex justify-between items-center mb-2">
                                    <span class="text-gray-700">جمع کل (پایه):</span>
                                    <span class="font-semibold">{{ number_format($cart['totals']['base_price']) }} ریال</span>
                                </div>
                                <div class="flex justify-between items-center mb-2">
                                    <span class="text-gray-700">ضریب طرح ({{ $planOptionDetails['name'] }}):</span>
                                    <span class="font-semibold">{{ $planOptionDetails['coefficient'] * $planOptionDetails['months'] }}%</span>
                                </div>
                                <div class="flex justify-between items-center text-xl font-bold text-indigo-700">
                                    <span>مبلغ نهایی (اقساطی):</span>
                                    <span>{{ number_format($cart['totals']['final_price']) }} ریال</span>
                                </div>
                                
                                <a href="{{ route('agent.cart.review') }}" class="block w-full text-center mt-6">
                                    <x-primary-button class="w-full justify-center text-lg py-3">
                                        ادامه و انتخاب مشتری &larr;
                                    </x-primary-button>
                                </a>
                            </div>
                        @endif
                    </div>
                </div>
            </div>

        </div>
    </div>
</x-app-layout>