@extends('frontend.layout.dash')

@section('content')
    @include('frontend.components.accordion')

    <div class="card mp-20 product-detail-page">
        <a href="{{ route('user.accounts.products') }}" class="product-detail-back">&larr; Back to products</a>

        <div class="product-detail-layout">
            <div class="product-detail-info">
                @if($product->image)
                    <div class="product-detail-image-wrap">
                        <img src="{{ asset($product->image) }}" alt="">
                    </div>
                @else
                    <div class="product-detail-image-wrap product-detail-image-placeholder">
                        <i class="ti ti-photo"></i>
                    </div>
                @endif
                <h1 class="product-detail-title">{{ $product->name }}</h1>
                <p class="product-detail-category">{{ $product->productCategory->name ?? '-' }}</p>
                @if($product->description)
                    <div class="product-detail-description">{!! nl2br(e($product->description)) !!}</div>
                @endif
                <div class="product-detail-meta">
                    <span class="product-detail-price">{{ $currency }}{{ number_format($product->price, 2) }} per account</span>
                    <span class="product-detail-stock">In stock: {{ $product->in_stock }}</span>
                </div>
            </div>

            <div class="product-detail-buy-wrap">
                <div class="product-detail-buy-card card">
                    <div class="card-body">
                        <h2 class="product-detail-buy-title">Buy now</h2>
                        @if($product->in_stock < 1)
                            <p class="product-detail-out-of-stock">Out of stock. Check back later.</p>
                        @else
                            <form id="account-purchase-form" class="product-detail-buy-form">
                                @csrf
                                <input type="hidden" name="product_id" value="{{ $product->id }}">
                                <div class="form-group">
                                    <label class="form-label" for="qty">Quantity <span class="required">*</span></label>
                                    <input type="number" class="form-control" name="quantity" id="qty" min="1" max="{{ $product->in_stock }}" value="1" required>
                                    <small class="text-muted">Max: {{ $product->in_stock }}</small>
                                </div>
                                <div class="product-detail-total-wrap">
                                    <span class="product-detail-total-label">Total</span>
                                    <span class="product-detail-total-amount" id="total-amount">{{ $currency }}{{ number_format($product->price, 2) }}</span>
                                </div>
                                <button type="submit" class="product-detail-purchase-btn" id="btn-purchase">
                                    <i class="ti ti-shopping-cart"></i> Purchase
                                </button>
                            </form>
                        @endif
                    </div>
                </div>
            </div>
        </div>
    </div>

    @if($related->isNotEmpty())
    <div class="card mp-20 product-detail-related">
        <h2 class="product-detail-related-title">Related products</h2>
        <div class="product-detail-related-grid">
            @foreach($related as $r)
                <a href="{{ route('user.accounts.product', $r->id) }}" class="product-detail-related-card card">
                    @if($r->image)
                        <img src="{{ asset($r->image) }}" alt="">
                    @else
                        <div class="product-detail-related-placeholder"><i class="ti ti-photo"></i></div>
                    @endif
                    <div class="card-body">
                        <h3 class="product-detail-related-name">{{ $r->name }}</h3>
                        <p class="product-detail-related-meta">{{ $currency }}{{ number_format($r->price, 2) }} · Stock: {{ $r->in_stock }}</p>
                    </div>
                </a>
            @endforeach
        </div>
    </div>
    @endif
@endsection

@push('script')
<script>
(function() {
    var price = {{ $product->price }};
    var currency = @json($currency);
    var qtyEl = document.getElementById('qty');
    var totalEl = document.getElementById('total-amount');
    if (qtyEl && totalEl) {
        function updateTotal() {
            var q = parseInt(qtyEl.value, 10) || 1;
            totalEl.textContent = currency + (price * q).toFixed(2);
        }
        qtyEl.addEventListener('input', updateTotal);
    }

    var form = document.getElementById('account-purchase-form');
    if (form) {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            var btn = document.getElementById('btn-purchase');
            btn.disabled = true;
            var fd = new FormData(form);
            fetch('{{ route("user.accounts.purchase") }}', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'Accept': 'application/json',
                },
                body: fd
            })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                btn.disabled = false;
                if (data.status === 'success') {
                    if (window.iziToast) iziToast.success({ message: data.message, position: 'topRight' });
                    window.location.href = '{{ route("user.log.account-orders.detail", ["id" => 0]) }}'.replace(/0$/, data.order_id);
                } else {
                    if (window.iziToast) iziToast.error({ message: data.message || 'Error', position: 'topRight' });
                }
            })
            .catch(function() {
                btn.disabled = false;
                if (window.iziToast) iziToast.error({ message: 'Request failed', position: 'topRight' });
            });
        });
    }
})();
</script>
@endpush
