@extends('layouts.app')

@section('title', 'Detail Produk')

@section('content')
<div class="container px-4 py-3">
    <a href="{{ route('product.index') }}" class="btn btn-secondary mb-3">
        ← Kembali
    </a>

    {{-- Multiple Images Gallery --}}
    <div class="card shadow-pink mb-4">
        <div class="row g-0">
            <div class="col-md-5">
                {{-- Main Image / Primary Image --}}
                <div class="product-gallery">
                    <div class="main-image-container mb-3">
                        @php
                            $primaryImage = $produk->images->where('is_primary', true)->first();
                            $allImages = $produk->images->sortBy('order');
                        @endphp
                        
                        @if($primaryImage)
                            <img id="mainProductImage" 
                                 src="{{ asset('storage/'.$primaryImage->foto) }}" 
                                 class="img-fluid rounded-start w-100 main-image"
                                 style="object-fit: cover; height: 400px; cursor: pointer;"
                                 onclick="openImageModal('{{ asset('storage/'.$primaryImage->foto) }}')">
                        @elseif($allImages->count() > 0)
                            <img id="mainProductImage" 
                                 src="{{ asset('storage/'.$allImages->first()->foto) }}" 
                                 class="img-fluid rounded-start w-100 main-image"
                                 style="object-fit: cover; height: 400px; cursor: pointer;"
                                 onclick="openImageModal('{{ asset('storage/'.$allImages->first()->foto) }}')">
                        @else
                            <img src="{{ asset('images/no-image.png') }}" 
                                 class="img-fluid rounded-start w-100"
                                 style="object-fit: cover; height: 400px;">
                        @endif
                    </div>
                    
                    {{-- Thumbnail Images --}}
                    @if($allImages->count() > 1)
                        <div class="thumbnail-container d-flex gap-2 mt-2 flex-wrap">
                            @foreach($allImages as $index => $image)
                                <div class="thumbnail-item {{ $index == 0 ? 'active' : '' }}" 
                                     onclick="changeMainImage('{{ asset('storage/'.$image->foto) }}', this)">
                                    <img src="{{ asset('storage/'.$image->foto) }}" 
                                         class="img-fluid rounded"
                                         style="width: 80px; height: 80px; object-fit: cover; cursor: pointer; border: 2px solid {{ $index == 0 ? '#ec4899' : 'transparent' }};"
                                         onmouseover="this.style.opacity='0.8'"
                                         onmouseout="this.style.opacity='1'">
                                </div>
                            @endforeach
                        </div>
                        
                        {{-- Info jumlah foto --}}
                        <div class="mt-2 text-muted small">
                            <i class="bi bi-images"></i> {{ $allImages->count() }} foto produk
                            @if($allImages->count() > 1)
                                <span class="ms-2">| Klik foto untuk memperbesar</span>
                            @endif
                        </div>
                    @elseif($allImages->count() == 1)
                        <div class="mt-2 text-muted small">
                            <i class="bi bi-image"></i> 1 foto produk | Klik foto untuk memperbesar
                        </div>
                    @else
                        <div class="mt-2 text-muted small">
                            <i class="bi bi-image"></i> Belum ada foto produk
                        </div>
                    @endif
                </div>
            </div>
            
            <div class="col-md-7">
                <div class="card-body">
                    <h4 class="fw-bold text-pink-gradient">{{ $produk->nama_produk }}</h4>
                    <p><span class="badge bg-pink">{{ $produk->kategori->nama_kategori ?? 'Tanpa Kategori' }}</span></p>
                    <p class="fs-3 fw-bold text-pink">Rp {{ number_format($produk->harga, 0, ',', '.') }}</p>
                    <p>Stok: <span class="fw-semibold {{ $produk->stok <= 5 ? 'text-danger' : 'text-success' }}">{{ $produk->stok }}</span></p>
                    <p>Terjual: <span class="fw-semibold">{{ $produk->terjual ?? 0 }}</span></p>
                    <p>Kadaluarsa: {{ $produk->tanggal_kadaluarsa ? \Carbon\Carbon::parse($produk->tanggal_kadaluarsa)->format('d/m/Y') : '-' }}</p>
                    
                    @auth
                        @if(Auth::user()->role == 'pengguna')
                            <form action="{{ route('cart.add', $produk->produk_id) }}" method="POST" class="mt-3">
                                @csrf
                                <div class="row g-2 align-items-center">
                                    <div class="col-auto">
                                        <label class="form-label mb-0">Jumlah:</label>
                                    </div>
                                    <div class="col-auto">
                                        <input type="number" name="jumlah" value="1" min="1" max="{{ $produk->stok }}" class="form-control" style="width: 80px;" required {{ $produk->is_expired ? 'disabled' : '' }}>
                                    </div>
                                    <div class="col-auto">
                                        <button type="submit" class="btn btn-pink-glow" {{ ($produk->stok < 1 || $produk->is_expired) ? 'disabled' : '' }}>
                                            <i class="bi bi-cart-plus"></i> {{ $produk->is_expired ? 'Produk Kadaluwarsa' : 'Tambah ke Keranjang' }}
                                        </button>
                                    </div>
                                </div>
                                @if($produk->is_expired)
                                    <div class="alert alert-danger mt-3 py-2 px-3 border-0 small rounded-3">
                                        <i class="bi bi-exclamation-octagon-fill me-2"></i>
                                        Mohon maaf, produk ini sudah melewati tanggal kadaluwarsa dan tidak dapat dipesan kembali.
                                    </div>
                                @endif
                            </form>
                        @endif
                    @endauth
                </div>
            </div>
        </div>
    </div>

    {{-- Section Ulasan Produk --}}
    <div class="row mt-4">
        <div class="col-12">
            <div class="reviews-section">
                <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-3">
                    <h4 class="fw-bold text-pink-gradient mb-0">
                        <i class="bi bi-chat-dots-fill me-2"></i>
                        Ulasan Produk
                    </h4>
                    <div class="rating-summary">
                        <span class="fs-2 fw-bold text-warning">{{ number_format($produk->average_rating, 1) }}</span>
                        <div class="stars-display d-inline-block ms-2">
                            @for($i = 1; $i <= 5; $i++)
                                @if($i <= round($produk->average_rating))
                                    <i class="bi bi-star-fill text-warning"></i>
                                @else
                                    <i class="bi bi-star text-warning"></i>
                                @endif
                            @endfor
                        </div>
                        <span class="text-muted ms-2">({{ $produk->reviews_count }} ulasan)</span>
                    </div>
                </div>
                
                {{-- Rating Distribution --}}
                @if($produk->reviews_count > 0)
                <div class="rating-distribution mb-4">
                    @php
                        $distribution = $produk->rating_distribution;
                    @endphp
                    @for($rating = 5; $rating >= 1; $rating--)
                        @php $count = $distribution[$rating] ?? 0; @endphp
                        @if($count > 0)
                            <div class="distribution-row d-flex align-items-center gap-2 mb-2">
                                <div class="rating-label" style="width: 45px;">{{ $rating }} ★</div>
                                <div class="progress flex-grow-1" style="height: 8px;">
                                    <div class="progress-bar bg-warning" style="width: {{ ($count / $produk->reviews_count) * 100 }}%"></div>
                                </div>
                                <div class="rating-count" style="width: 45px;">{{ $count }}</div>
                            </div>
                        @endif
                    @endfor
                </div>
                @endif
                
                {{-- List Reviews --}}
                <div class="reviews-list">
                    @php
                        $reviews = $produk->reviews()->with('user')->latest()->get();
                    @endphp
                    
                    @forelse($reviews as $review)
                        <div class="review-card mb-3 p-3 rounded-3 border">
                            <div class="d-flex justify-content-between align-items-start mb-2 flex-wrap gap-2">
                                <div>
                                    <div class="stars-display mb-1">
                                        @for($i = 1; $i <= 5; $i++)
                                            @if($i <= $review->rating)
                                                <i class="bi bi-star-fill text-warning"></i>
                                            @else
                                                <i class="bi bi-star text-warning"></i>
                                            @endif
                                        @endfor
                                    </div>
                                    <div class="reviewer-info">
                                        <strong>{{ $review->user->username ?? 'Pengguna' }}</strong>
                                        <small class="text-muted ms-2">{{ $review->created_at->diffForHumans() }}</small>
                                    </div>
                                </div>
                                @auth
                                    @if($review->user_id == Auth::id())
                                        <span class="badge bg-pink">Ulasan Anda</span>
                                    @endif
                                @endauth
                            </div>
                            @if($review->komentar)
                                <p class="review-comment mb-0 text-muted">{{ $review->komentar }}</p>
                            @else
                                <p class="review-comment mb-0 text-muted fst-italic">Tidak ada komentar</p>
                            @endif
                        </div>
                    @empty
                        <div class="text-center py-5">
                            <i class="bi bi-chat-dots fs-1 text-muted"></i>
                            <p class="text-muted mt-2">Belum ada ulasan untuk produk ini.</p>
                            <small class="text-muted">Jadilah yang pertama memberikan ulasan!</small>
                        </div>
                    @endforelse
                </div>
            </div>
        </div>
    </div>
</div>

{{-- Modal untuk preview gambar besar --}}
<div class="modal fade" id="imageModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-xl">
        <div class="modal-content bg-transparent border-0">
            <div class="modal-body p-0 text-end">
                <button type="button" class="btn btn-light rounded-circle mb-2" data-bs-dismiss="modal" style="position: relative; z-index: 1;">
                    <i class="bi bi-x-lg"></i>
                </button>
                <img id="modalImage" src="" class="img-fluid rounded w-100" style="max-height: 80vh; object-fit: contain;">
            </div>
        </div>
    </div>
</div>

<style>
.text-pink-gradient {
    background: linear-gradient(135deg, #ec4899, #db2777);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.btn-pink-glow {
    background: linear-gradient(135deg, #ec4899, #db2777);
    border: none;
    color: white;
    font-weight: 600;
    border-radius: 8px;
    padding: 0.5rem 1.5rem;
    transition: all 0.3s ease;
}

.btn-pink-glow:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(236, 72, 153, 0.4);
    color: white;
}

.btn-pink-glow:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

.shadow-pink {
    box-shadow: 0 4px 25px rgba(236, 72, 153, 0.15);
}

.bg-pink {
    background: linear-gradient(135deg, #ec4899, #db2777);
    color: white;
}

.text-pink {
    color: #ec4899;
}

.reviews-section {
    background: white;
    border-radius: 20px;
    padding: 1.5rem;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.review-card {
    transition: all 0.3s ease;
    background: #fafafa;
}

.review-card:hover {
    transform: translateX(5px);
    background: white;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.stars-display i {
    font-size: 0.9rem;
    margin-right: 2px;
}

.rating-distribution {
    max-width: 400px;
}

.progress {
    background-color: #e5e7eb;
    border-radius: 10px;
    overflow: hidden;
}

.progress-bar {
    border-radius: 10px;
    transition: width 0.5s ease;
}

.card {
    border: none;
    border-radius: 20px;
    overflow: hidden;
}

.card-body {
    padding: 1.5rem;
}

/* Gallery Styles */
.product-gallery {
    padding: 1rem;
    background: #fafafa;
    border-radius: 12px;
    height: 100%;
}

.main-image-container {
    overflow: hidden;
    border-radius: 12px;
    background: #f0f0f0;
}

.main-image {
    transition: transform 0.3s ease;
}

.main-image:hover {
    transform: scale(1.05);
}

.thumbnail-container {
    overflow-x: auto;
    padding-bottom: 5px;
}

.thumbnail-item {
    transition: all 0.2s ease;
}

.thumbnail-item:hover {
    transform: translateY(-2px);
}

.thumbnail-item.active img {
    border-color: #ec4899 !important;
    box-shadow: 0 0 0 2px rgba(236, 72, 153, 0.3);
}

/* Modal Styles */
.modal-content.bg-transparent {
    background: transparent !important;
}

.modal.show .modal-dialog {
    margin: 1.75rem auto;
}

@media (max-width: 768px) {
    .reviews-section {
        padding: 1rem;
    }
    
    .rating-summary {
        width: 100%;
    }
    
    .product-gallery {
        padding: 0.5rem;
    }
    
    .main-image {
        height: 300px !important;
    }
    
    .thumbnail-item img {
        width: 60px !important;
        height: 60px !important;
    }
}
</style>

<script>
    // Fungsi untuk mengganti gambar utama
    function changeMainImage(imageUrl, element) {
        // Update gambar utama
        document.getElementById('mainProductImage').src = imageUrl;
        
        // Update active state pada thumbnail
        const thumbnails = document.querySelectorAll('.thumbnail-item');
        thumbnails.forEach(thumb => {
            thumb.classList.remove('active');
            const img = thumb.querySelector('img');
            if (img) {
                img.style.borderColor = 'transparent';
            }
        });
        
        element.classList.add('active');
        const activeImg = element.querySelector('img');
        if (activeImg) {
            activeImg.style.borderColor = '#ec4899';
        }
    }
    
    // Fungsi untuk membuka modal gambar besar
    function openImageModal(imageUrl) {
        const modal = new bootstrap.Modal(document.getElementById('imageModal'));
        document.getElementById('modalImage').src = imageUrl;
        modal.show();
    }
    
    // Keyboard navigation untuk thumbnail (optional)
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            const modal = bootstrap.Modal.getInstance(document.getElementById('imageModal'));
            if (modal) {
                modal.hide();
            }
        }
    });
</script>
@endsection