@extends('layouts.frontend')

@section('title', 'Keranjang Belanja')

@section('content')
    <div class="container py-5 mt-4">
        <h2 class="mb-4 fw-bold">Keranjang Belanja</h2>

        @if ($cart->count() > 0)
            <div class="row g-5">
                <div class="col-lg-8">
                    <div class="card border-0 shadow-sm">
                        <div class="card-body p-0">
                            <div class="table-responsive">
                                <table class="table align-middle mb-0">
                                    <thead class="border-bottom border-1">
                                        <tr>
                                            {{-- CHECKBOX HEADER  --}}
                                            <th class="py-3 ps-4 border-0" style="width: 50px;">
                                                <div class="form-check">
                                                    <input class="form-check-input cursor-pointer" type="checkbox" id="check-all" checked>
                                                </div>
                                            </th>
                                            <th class="py-3 border-0">Produk</th>
                                            <th class="py-3 border-0">Harga</th>
                                            <th class="py-3 border-0">Jumlah</th>
                                            <th class="py-3 border-0">Total</th>
                                            <th class="py-3 pe-4 border-0 text-end"></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @php $total_belanja = 0; @endphp
                                        
                                        @foreach ($cart as $item)
                                            @php
                                                $total_per_item = $item->produk->harga * $item->quantity;
                                                $total_belanja += $total_per_item;
                                            @endphp
                                            
                                            <tr data-id="{{ $item->id }}" class="border-bottom">
                                                {{-- CHECKBOX ITEM --}}
                                                <td class="ps-4 py-3 align-middle">
                                                    <div class="form-check">
                                                        <input class="form-check-input item-check cursor-pointer" 
                                                            type="checkbox" 
                                                            value="{{ $item->id }}" 
                                                            data-subtotal="{{ $total_per_item }}" 
                                                            checked>
                                                    </div>
                                                </td>

                                                <td class="py-3">
                                                    <div class="d-flex align-items-center">
                                                        <img src="{{ $item->produk->foto_produk ? asset('storage/' . $item->produk->foto_produk) : asset('template/frontend/img/vegetable-item-3.png') }}"
                                                            class="rounded-3 me-3"
                                                            style="width: 60px; height: 60px; object-fit: cover;">
                                                        <span class="fw-bold text-dark">{{ $item->produk->nama_produk }}</span>
                                                    </div>
                                                </td>
                                                <td class="text-muted">Rp
                                                    {{ number_format($item->produk->harga, 0, ',', '.') }}
                                                </td>
                                                <td class="align-middle text-center">
                                                    <div class="input-group input-group-sm flex-nowrap mx-auto shadow-sm"
                                                        style="width: 120px;">

                                                        <button class="btn btn-light border btn-minus-custom" type="button">
                                                            <i class="fas fa-minus text-secondary" style="font-size: 0.8rem;"></i>
                                                        </button>

                                                        <input type="text"
                                                            class="form-control text-center border-top border-bottom border-light bg-white qty-input px-0"
                                                            value="{{ $item->quantity }}" readonly style="min-width: 40px;">

                                                        <button class="btn btn-light border btn-plus-custom" type="button">
                                                            <i class="fas fa-plus text-secondary" style="font-size: 0.8rem;"></i>
                                                        </button>
                                                    </div>
                                                </td>
                                                <td class="fw-bold text-dark">Rp {{ number_format($total_per_item, 0, ',', '.') }}
                                                </td>
                                                <td class="pe-4 text-end">
                                                    <form action="{{ route('cart.remove') }}" method="POST" class="d-inline">
                                                        @csrf
                                                        @method('DELETE')
                                                        <input type="hidden" name="id" value="{{ $item->id }}">
                                                        <button class="btn btn-link text-danger p-0 text-decoration-none"
                                                            onclick="return confirm('Hapus item ini?')">
                                                            <i class="fa fa-trash"></i>
                                                        </button>
                                                    </form>
                                                </td>
                                            </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-lg-4">
                    <div class="card border-0 shadow-sm bg-light">
                        <div class="card-body p-4">
                            <h5 class="fw-bold mb-4">Ringkasan Belanja</h5>
                            <div class="d-flex justify-content-between mb-3">
                                <span class="text-muted">Subtotal</span>
                                <span class="fw-bold" id="subtotal-display">Rp {{ number_format($total_belanja, 0, ',', '.') }}</span>
                            </div>
                            <div class="d-flex justify-content-between mb-4 border-top pt-3">
                                <span class="fw-bold fs-5">Total</span>
                                <span class="fw-bold fs-5 text-primary" id="total-display">Rp
                                    {{ number_format($total_belanja, 0, ',', '.') }}</span>
                            </div>
                            
                            {{-- Tombol Checkout Dinamis --}}
                            <a href="{{ route('checkout') }}" id="btn-checkout" class="btn btn-primary w-100 rounded-pill py-3 fw-bold shadow-sm">
                                Checkout Sekarang
                            </a>
                            
                            <a href="{{ route('shop') }}" class="btn btn-link text-muted w-100 mt-2 text-decoration-none small">
                                Lanjut Belanja
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        @else
            <div class="text-center py-5">
                <div class="mb-3">
                    <i class="fas fa-shopping-basket fa-4x text-muted opacity-25"></i>
                </div>
                <h4 class="text-muted fw-bold">Keranjang Kosong</h4>
                <p class="text-muted mb-4">Yuk isi dengan beras berkualitas kami.</p>
                <a href="{{ route('shop') }}" class="btn btn-primary rounded-pill px-5 py-3">
                    Mulai Belanja
                </a>
            </div>
        @endif
    </div>
@endsection

@section('js')
    <script>
        $(document).ready(function () {
            // --- LOGIKA QUANTITY  ---
            $(".btn-plus-custom, .btn-minus-custom").off("click");

            $(".btn-plus-custom").click(function (e) {
                e.preventDefault();
                var ele = $(this);
                var input = ele.closest("tr").find(".qty-input");
                var currentVal = parseInt(input.val()) || 0;
                var newVal = currentVal + 1;
                input.val(newVal);
                updateCart(ele.closest("tr").attr("data-id"), newVal);
            });

            $(".btn-minus-custom").click(function (e) {
                e.preventDefault();
                var ele = $(this);
                var input = ele.closest("tr").find(".qty-input");
                var currentVal = parseInt(input.val()) || 0;
                if (currentVal > 1) {
                    var newVal = currentVal - 1;
                    input.val(newVal);
                    updateCart(ele.closest("tr").attr("data-id"), newVal);
                }
            });

            function updateCart(id, qty) {
                $.ajax({
                    url: "{{ route('cart.update') }}",
                    method: "patch",
                    data: {
                        _token: '{{ csrf_token() }}',
                        id: id,
                        quantity: qty
                    },
                    success: function (response) {
                        window.location.reload();
                    },
                    error: function(xhr) {
                        alert("Gagal update. Pastikan login.");
                    }
                });
            }

            // --- LOGIKA CHECKBOX  ---
            const formatRupiah = (number) => {
                return new Intl.NumberFormat('id-ID', { 
                    style: 'currency', 
                    currency: 'IDR',
                    minimumFractionDigits: 0,
                    maximumFractionDigits: 0
                }).format(number).replace('Rp', 'Rp '); 
            }

            function updateSummary() {
                let total = 0;
                let selectedIds = [];
                
                $('.item-check:checked').each(function() {
                    total += parseFloat($(this).data('subtotal'));
                    selectedIds.push($(this).val());
                });
                $('#subtotal-display').text(formatRupiah(total));
                $('#total-display').text(formatRupiah(total));

                let baseUrl = "{{ route('checkout') }}";
                let btn = $('#btn-checkout');

                if(selectedIds.length === 0) {
                    btn.addClass('disabled');
                    btn.attr('href', '#');
                } else {
                    btn.removeClass('disabled');
                    let newUrl = baseUrl + "?cart_ids=" + selectedIds.join(',');
                    btn.attr('href', newUrl);
                }
            }

            $('#check-all').change(function() {
                let isChecked = $(this).prop('checked');
                $('.item-check').prop('checked', isChecked);
                updateSummary();
            });

            $('.item-check').change(function() {
                let allChecked = $('.item-check').length === $('.item-check:checked').length;
                $('#check-all').prop('checked', allChecked);
                
                updateSummary();
            });

            updateSummary();
        });
    </script>
@endsection