@extends('layouts.main')

@section('title', 'My Product Inquiries')

@section('content')
<div class="min-h-screen py-6 sm:py-8">
    <div class="w-full max-w-[1200px] mx-auto px-3 sm:px-4">
        <!-- Header -->
        <div class="mb-6 sm:mb-8">
            <div class="flex flex-col md:flex-row md:justify-between md:items-center gap-4">
                <div>
                    <h1 class="text-2xl sm:text-3xl font-bold text-gray-900">Penawaran Produk Saya</h1>
                    <p class="mt-1 text-sm sm:text-base text-gray-600">Riwayat penawaran dan pertanyaan produk</p>
                </div>
                <div class="flex gap-2 sm:gap-3">
                    <a href="{{ route('all') }}" 
                        class="inline-flex items-center px-3 sm:px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-lg transition-colors">
                        <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                        </svg>
                        Lihat Produk
                    </a>
                    <a href="{{ route('user.dashboard') }}" 
                        class="inline-flex items-center px-3 sm:px-4 py-2 text-sm text-blue-600 hover:text-blue-800 font-medium">
                        <svg class="w-4 h-4 mr-2" fill="currentColor" viewBox="0 0 20 20">
                            <path fill-rule="evenodd" d="M9.707 16.707a1 1 0 01-1.414 0l-6-6a1 1 0 010-1.414l6-6a1 1 0 011.414 1.414L5.414 9H17a1 1 0 110 2H5.414l4.293 4.293a1 1 0 010 1.414z" clip-rule="evenodd" />
                        </svg>
                        Kembali
                    </a>
                </div>
            </div>
        </div>

        <!-- Search and Filter -->
        <div class="bg-white rounded-lg border border-gray-200 p-4 sm:p-6 mb-6">
            <div class="flex flex-col md:flex-row gap-3 sm:gap-4">
                <div class="flex-1">
                    <div class="relative">
                        <input type="text" id="searchInput" placeholder="Cari ID penawaran, produk, atau informasi lainnya..." 
                            class="w-full pl-10 pr-4 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:outline-none">
                        <svg class="absolute left-3 top-2.5 w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                        </svg>
                    </div>
                </div>
                <div class="md:w-48">
                    <select id="statusFilter" class="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:outline-none">
                        <option value="">Semua Status</option>
                        <option value="unread">Belum Dibaca</option>
                        <option value="read">Sudah Dibaca</option>
                    </select>
                </div>
            </div>
        </div>

        <!-- Desktop Table View -->
        <div class="hidden lg:block bg-white rounded-lg border border-gray-200 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="min-w-full">
                    <thead class="bg-blue-50 border-b border-gray-200">
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">No</th>
                            <th class="px-4 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Nama</th>
                            <th class="px-4 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider hidden md:table-cell">Produk</th>
                            <th class="px-4 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider hidden lg:table-cell">Email</th>
                            <th class="px-4 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider hidden lg:table-cell">Telepon</th>
                            <th class="px-4 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider hidden sm:table-cell">Pesan</th>
                            <th class="px-4 py-3 text-center text-xs font-semibold text-gray-700 uppercase tracking-wider">Status</th>
                            <th class="px-4 py-3 text-center text-xs font-semibold text-gray-700 uppercase tracking-wider hidden md:table-cell">Tanggal</th>
                            <th class="px-4 py-3 text-center text-xs font-semibold text-gray-700 uppercase tracking-wider">Aksi</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        @forelse($inquiries as $inquiry)
                            <tr class="hover:bg-gray-50 transition-colors duration-200"
                                data-inquiry-id="{{ $inquiry->id }}"
                                data-product="{{ strtolower($inquiry->product->product_title ?? '') }}"
                                data-name="{{ strtolower($inquiry->name ?? '') }}"
                                data-message="{{ strtolower($inquiry->message ?? '') }}"
                                data-status="{{ $inquiry->is_read ? 'read' : 'unread' }}">
                                <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-900 text-center">
                                    {{ $loop->iteration + $inquiries->firstItem() - 1 }}
                                </td>
                                <td class="px-4 py-3 whitespace-nowrap text-sm font-medium text-gray-900">
                                    {{ $inquiry->name }}
                                </td>
                                <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-600 hidden md:table-cell">
                                    <div class="flex items-center max-w-xs">
                                        @if($inquiry->product && $inquiry->product->product_image)
                                            <img src="{{ asset('uploads/products/' . $inquiry->product->product_image) }}" 
                                                alt="{{ $inquiry->product->product_title }}" 
                                                class="w-10 h-10 rounded-lg object-contain mr-3 bg-gray-50 p-1 flex-shrink-0">
                                        @endif
                                        <div class="min-w-0 flex-1">
                                            <div class="truncate font-medium">{{ $inquiry->product->product_title ?? 'N/A' }}</div>
                                            @if($inquiry->product)
                                                <div class="text-xs text-gray-500">ID: {{ $inquiry->product->id }}</div>
                                            @endif
                                        </div>
                                    </div>
                                </td>
                                <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-600 hidden lg:table-cell">
                                    <div class="max-w-xs truncate">{{ $inquiry->email }}</div>
                                </td>
                                <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-600 hidden lg:table-cell">
                                    {{ $inquiry->phone }}
                                </td>
                                <td class="px-4 py-3 text-sm text-gray-700 max-w-xs hidden sm:table-cell">
                                    @php
                                        $raw = $inquiry->message ?? '';
                                        $lines = preg_split("/(\r\n|\n|\r)/", $raw);
                                        $type = null;
                                        $addons = [];
                                        $hasAddonsLine = false;
                                        if (!empty($lines)) {
                                            $first = $lines[0] ?? '';
                                            $second = $lines[1] ?? '';
                                            if (substr($first, 0, 14) === '[REQUEST_TYPE]') {
                                                $type = trim(substr($first, 14));
                                            }
                                            if (substr($second, 0, 8) === '[ADDONS]') {
                                                $hasAddonsLine = true;
                                                $matches = [];
                                                if (preg_match('/^\[ADDONS\]\s*(\[[\s\S]*\])$/', $second, $matches)) {
                                                    $decoded = json_decode($matches[1], true);
                                                    if (is_array($decoded)) { $addons = $decoded; }
                                                }
                                            }
                                        }
                                        $startIdx = 0;
                                        if ($type) { $startIdx++; }
                                        if ($hasAddonsLine) { $startIdx++; }
                                        if (!empty($lines) && isset($lines[$startIdx]) && trim($lines[$startIdx]) === '') { $startIdx++; }
                                        $plain = implode("\n", array_slice($lines, $startIdx));
                                        $badgeText = $type === 'custom_addon' ? 'Custom Add-on' : ($type === 'custom_new' ? 'Custom Baru' : ($type ? 'Katalog' : null));
                                        $badgeCls = $type === 'custom_addon' ? 'bg-yellow-100 text-yellow-800' : ($type === 'custom_new' ? 'bg-red-100 text-red-800' : 'bg-blue-100 text-blue-800');
                                    @endphp
                                    <div class="space-y-1">
                                        @if($badgeText)
                                            <div class="mb-1">
                                                <span class="inline-flex items-center px-2 py-0.5 text-xs font-semibold rounded-full {{ $badgeCls }}">
                                                    {{ $badgeText }}
                                                </span>
                                            </div>
                                        @endif
                                        <div class="truncate" title="{{ $plain ?: $inquiry->message }}">
                                            {{ Str::limit($plain ?: $inquiry->message, 50) }}
                                        </div>
                                    </div>
                                </td>
                                <td class="px-4 py-3 whitespace-nowrap text-center">
                                    @if($inquiry->is_read)
                                        <span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                            <svg class="w-3 h-3 mr-1" fill="currentColor" viewBox="0 0 20 20">
                                                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.707a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 10-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
                                            </svg>
                                            Dibaca
                                        </span>
                                    @else
                                        <span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                                            <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                            </svg>
                                            Belum Dibaca
                                        </span>
                                    @endif
                                </td>
                                <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500 text-center hidden md:table-cell">
                                    {{ $inquiry->created_at->format('d M Y H:i') }}
                                </td>
                                <td class="px-4 py-3 whitespace-nowrap text-center">
                                    <a href="{{ route('user.inquiries.show', $inquiry) }}" 
                                        class="inline-flex items-center px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded-md text-xs font-medium transition-colors">
                                        <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                                        </svg>
                                        Detail
                                    </a>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="9" class="px-6 py-16 text-center">
                                    <div class="flex flex-col items-center">
                                        <div class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4">
                                            <svg class="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                            </svg>
                                        </div>
                                        <p class="text-gray-500 text-lg font-medium">Belum ada penawaran produk</p>
                                        <p class="text-gray-400 text-sm mt-1">Mulai dengan melihat produk kami</p>
                                        <a href="{{ route('all') }}" 
                                            class="mt-4 inline-flex items-center px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-lg transition-colors">
                                            <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                                            </svg>
                                            Lihat Produk
                                        </a>
                                    </div>
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Mobile Card View -->
        <div class="lg:hidden space-y-4">
            @forelse($inquiries as $inquiry)
                <div class="bg-white rounded-lg border border-gray-200 overflow-hidden"
                    data-inquiry-id="{{ $inquiry->id }}"
                    data-product="{{ strtolower($inquiry->product->product_title ?? '') }}"
                    data-name="{{ strtolower($inquiry->name ?? '') }}"
                    data-message="{{ strtolower($inquiry->message ?? '') }}"
                    data-status="{{ $inquiry->is_read ? 'read' : 'unread' }}">
                    <!-- Card Header -->
                    <div class="px-4 py-3 bg-blue-50 border-b border-gray-200 flex items-center justify-between">
                        <div class="flex items-center gap-2">
                            <span class="text-xs font-medium text-gray-500">No. {{ $loop->iteration + $inquiries->firstItem() - 1 }}</span>
                            <span class="text-xs text-gray-400">•</span>
                            <span class="text-sm font-semibold text-gray-900">{{ $inquiry->name }}</span>
                        </div>
                        <a href="{{ route('user.inquiries.show', $inquiry) }}"
                            class="inline-flex items-center px-2 py-1 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors text-xs">
                            <svg class="w-3.5 h-3.5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                            </svg>
                            Detail
                        </a>
                    </div>

                    <!-- Card Body -->
                    <div class="p-4 space-y-3">
                        <!-- Product Info -->
                        @if($inquiry->product)
                        <div class="flex items-start gap-3">
                            @if($inquiry->product->product_image)
                                <img src="{{ asset('uploads/products/' . $inquiry->product->product_image) }}" 
                                    alt="{{ $inquiry->product->product_title }}" 
                                    class="w-16 h-16 rounded-lg object-contain bg-gray-50 p-1 flex-shrink-0">
                            @endif
                            <div class="flex-1 min-w-0">
                                <p class="text-xs text-gray-600 mb-1">Produk</p>
                                <p class="text-sm font-semibold text-gray-900">{{ $inquiry->product->product_title ?? 'N/A' }}</p>
                            </div>
                        </div>
                        @endif

                        <!-- Message Preview -->
                        <div>
                            <p class="text-xs text-gray-600 mb-1">Pesan</p>
                            @php
                                $raw = $inquiry->message ?? '';
                                $lines = preg_split("/(\r\n|\n|\r)/", $raw);
                                $type = null;
                                $hasAddonsLine = false;
                                if (!empty($lines)) {
                                    $first = $lines[0] ?? '';
                                    $second = $lines[1] ?? '';
                                    if (substr($first, 0, 14) === '[REQUEST_TYPE]') {
                                        $type = trim(substr($first, 14));
                                    }
                                    if (substr($second, 0, 8) === '[ADDONS]') {
                                        $hasAddonsLine = true;
                                    }
                                }
                                $startIdx = 0;
                                if ($type) { $startIdx++; }
                                if ($hasAddonsLine) { $startIdx++; }
                                if (!empty($lines) && isset($lines[$startIdx]) && trim($lines[$startIdx]) === '') { $startIdx++; }
                                $plain = implode("\n", array_slice($lines, $startIdx));
                                $badgeText = $type === 'custom_addon' ? 'Custom Add-on' : ($type === 'custom_new' ? 'Custom Baru' : ($type ? 'Katalog' : null));
                                $badgeCls = $type === 'custom_addon' ? 'bg-yellow-100 text-yellow-800' : ($type === 'custom_new' ? 'bg-red-100 text-red-800' : 'bg-blue-100 text-blue-800');
                            @endphp
                            <div class="space-y-1">
                                @if($badgeText)
                                    <span class="inline-flex items-center px-2 py-0.5 text-xs font-semibold rounded-full {{ $badgeCls }}">
                                        {{ $badgeText }}
                                    </span>
                                @endif
                                <p class="text-sm text-gray-700 line-clamp-2">{{ Str::limit($plain ?: $inquiry->message, 80) }}</p>
                            </div>
                        </div>

                        <!-- Status & Date -->
                        <div class="grid grid-cols-2 gap-3 pt-3 border-t border-gray-200">
                            <div>
                                <p class="text-xs text-gray-600 mb-1">Status</p>
                                @if($inquiry->is_read)
                                    <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                        <svg class="w-3 h-3 mr-1" fill="currentColor" viewBox="0 0 20 20">
                                            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.707a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 10-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
                                        </svg>
                                        Dibaca
                                    </span>
                                @else
                                    <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                                        <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                        </svg>
                                        Belum Dibaca
                                    </span>
                                @endif
                            </div>
                            <div>
                                <p class="text-xs text-gray-600 mb-1">Tanggal</p>
                                <p class="text-xs font-medium text-gray-900">{{ $inquiry->created_at->format('d M Y') }}</p>
                            </div>
                        </div>
                    </div>
                </div>
            @empty
                <div class="bg-white rounded-lg border border-gray-200 p-8 text-center">
                    <div class="flex flex-col items-center">
                        <div class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4">
                            <svg class="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                            </svg>
                        </div>
                        <p class="text-gray-500 text-lg font-medium">Belum ada penawaran produk</p>
                        <p class="text-gray-400 text-sm mt-1">Mulai dengan melihat produk kami</p>
                        <a href="{{ route('all') }}" 
                            class="mt-4 inline-flex items-center px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-lg transition-colors">
                            <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                            </svg>
                            Lihat Produk
                        </a>
                    </div>
                </div>
            @endforelse
        </div>

        <!-- Pagination -->
        @if($inquiries->count() > 0)
            <div class="mt-6 flex justify-center">
                {{ $inquiries->links() }}
            </div>
        @endif
    </div>
</div>

<!-- SweetAlert2 CDN -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    // Search functionality
    document.getElementById('searchInput').addEventListener('input', function() {
        applyFilters();
    });

    // Status filter functionality
    document.getElementById('statusFilter').addEventListener('change', function() {
        applyFilters();
    });

    function applyFilters() {
        const searchTerm = document.getElementById('searchInput').value.toLowerCase();
        const statusFilter = document.getElementById('statusFilter').value.toLowerCase();

        // Filter desktop table rows
        const desktopRows = document.querySelectorAll('tbody tr');
        desktopRows.forEach(row => {
            const inquiryId = row.dataset.inquiryId || '';
            const product = row.dataset.product || '';
            const name = row.dataset.name || '';
            const message = row.dataset.message || '';
            const text = row.textContent.toLowerCase();
            
            // Search filter
            const matchesSearch = !searchTerm || 
                text.includes(searchTerm) || 
                inquiryId.includes(searchTerm) ||
                product.includes(searchTerm) ||
                name.includes(searchTerm) ||
                message.includes(searchTerm);
            
            // Status filter
            const rowStatus = (row.dataset.status || '').toLowerCase();
            const matchesStatus = !statusFilter || rowStatus === statusFilter;

            if (matchesSearch && matchesStatus) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });

        // Filter mobile cards
        const mobileCards = document.querySelectorAll('.lg\\:hidden .space-y-4 > div');
        mobileCards.forEach(card => {
            const inquiryId = card.dataset.inquiryId || '';
            const product = card.dataset.product || '';
            const name = card.dataset.name || '';
            const message = card.dataset.message || '';
            const text = card.textContent.toLowerCase();
            
            // Search filter
            const matchesSearch = !searchTerm || 
                text.includes(searchTerm) || 
                inquiryId.includes(searchTerm) ||
                product.includes(searchTerm) ||
                name.includes(searchTerm) ||
                message.includes(searchTerm);
            
            // Status filter
            const cardStatus = (card.dataset.status || '').toLowerCase();
            const matchesStatus = !statusFilter || cardStatus === statusFilter;

            if (matchesSearch && matchesStatus) {
                card.style.display = '';
            } else {
                card.style.display = 'none';
            }
        });
    }
</script>
@endsection
