@extends('layouts.app')

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

@section('content')
<style>
/* Pink Theme Styles */
:root {
    --pink-50: #fdf2f8;
    --pink-100: #fce7f3;
    --pink-200: #fbcfe8;
    --pink-300: #f9a8d4;
    --pink-400: #f472b6;
    --pink-500: #ec4899;
    --pink-600: #db2777;
    --pink-700: #be185d;
    --pink-800: #9d174d;
    --pink-900: #831843;
}

.text-pink-800 { color: var(--pink-800) !important; }
.text-pink-600 { color: var(--pink-600) !important; }
.text-pink-700 { color: var(--pink-700) !important; }
.text-pink-400 { color: var(--pink-400) !important; }
.text-pink-300 { color: var(--pink-300) !important; }

.bg-pink-50 { background-color: var(--pink-50) !important; }
.bg-pink-100 { background-color: var(--pink-100) !important; }
.bg-pink-600 { background-color: var(--pink-600) !important; }
.border-pink-200 { border-color: var(--pink-200) !important; }
.border-pink-100 { border-color: var(--pink-100) !important; }

.bg-pink-gradient {
    background: linear-gradient(135deg, var(--pink-500) 0%, var(--pink-700) 100%) !important;
}

.btn-pink-gradient {
    background: linear-gradient(135deg, var(--pink-500) 0%, var(--pink-700) 100%) !important;
    border: none;
    color: white !important;
    transition: all 0.3s ease;
}

.btn-pink-gradient:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(236, 72, 153, 0.4) !important;
}

.btn-outline-pink {
    border: 2px solid var(--pink-500);
    color: var(--pink-600);
    background: transparent;
    transition: all 0.3s ease;
}

.btn-outline-pink:hover {
    background: var(--pink-500);
    color: white;
    border-color: var(--pink-500);
}

.btn-soft-pink {
    background: var(--pink-100);
    color: var(--pink-700);
    border: 1px solid var(--pink-200);
}

.btn-soft-pink:hover {
    background: var(--pink-200);
    color: var(--pink-800);
}

.btn-light-pink {
    background: var(--pink-50);
    color: var(--pink-700);
    border: 1px solid var(--pink-200);
}

.alert-pink-gradient {
    background: linear-gradient(135deg, var(--pink-50) 0%, #fff 100%);
    border-left: 4px solid var(--pink-500);
    border-radius: 8px;
}

.alert-soft-pink {
    background: linear-gradient(135deg, #fff0f7 0%, #fff 100%);
    border-left: 4px solid #f472b6;
    border-radius: 8px;
    color: #831843;
}

.product-image {
    width: 70px;
    height: 70px;
    object-fit: cover;
    border: 2px solid var(--pink-100);
    border-radius: 12px;
    transition: transform 0.2s ease;
}

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

.product-placeholder {
    width: 70px;
    height: 70px;
    background: linear-gradient(135deg, var(--pink-300) 0%, var(--pink-400) 100%);
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.hover-bg-pink-50:hover {
    background-color: var(--pink-50) !important;
}

.quantity-badge .badge {
    min-width: 60px;
    border-radius: 20px;
    font-size: 0.9rem;
}

.empty-cart-icon {
    animation: float 3s ease-in-out infinite;
}

@keyframes float {
    0%, 100% { transform: translateY(0); }
    50% { transform: translateY(-10px); }
}

.shadow-lg {
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1) !important;
}

.shadow-sm {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08) !important;
}

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

.table th {
    border-bottom: 2px solid var(--pink-200);
    font-weight: 600;
    text-transform: uppercase;
    font-size: 0.85rem;
    letter-spacing: 0.5px;
}

.table td {
    border-color: var(--pink-100);
    padding: 1rem 0.75rem;
    vertical-align: middle;
}

.badge {
    font-weight: 500;
    padding: 0.35em 0.65em;
}

.form-check-input:checked {
    background-color: var(--pink-500);
    border-color: var(--pink-500);
}

/* Custom scrollbar */
::-webkit-scrollbar {
    width: 8px;
}

::-webkit-scrollbar-track {
    background: var(--pink-50);
    border-radius: 10px;
}

::-webkit-scrollbar-thumb {
    background: var(--pink-300);
    border-radius: 10px;
}

::-webkit-scrollbar-thumb:hover {
    background: var(--pink-400);
}

@keyframes pulse {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.7; }
}

.pulse-animation {
    animation: pulse 2s infinite;
}

.image-container {
    position: relative;
    display: inline-block;
}

.image-badge {
    position: absolute;
    top: -8px;
    right: -8px;
    background: var(--pink-600);
    color: white;
    border-radius: 50%;
    width: 22px;
    height: 22px;
    font-size: 0.7rem;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
}
</style>

<div class="container-fluid px-4 py-4">
    <!-- Header -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex align-items-center justify-content-between flex-wrap gap-3">
                <div>
                    <h1 class="display-6 fw-bold text-pink-800">
                        <i class="fas fa-shopping-bag me-3"></i>Keranjang Belanja
                    </h1>
                    <p class="text-muted">Kelola produk yang ingin Anda beli</p>
                </div>
                <div class="d-flex gap-2">
                    <a href="{{ route('product.index') }}" class="btn btn-outline-pink">
                        <i class="fas fa-plus-circle me-2"></i>Tambah Produk
                    </a>
                    @if(!empty($cart) && count($cart) > 0)
                    <form action="{{ route('cart.clear') }}" method="POST" class="d-inline">
                        @csrf
                        <button type="submit" class="btn btn-light-pink" 
                                onclick="return confirm('Kosongkan seluruh keranjang?')">
                            <i class="fas fa-broom me-2"></i>Kosongkan
                        </button>
                    </form>
                    @endif
                </div>
            </div>
        </div>
    </div>

    <!-- Notifications -->
    @if(session('success'))
    <div class="alert alert-pink-gradient alert-dismissible fade show shadow-sm" role="alert">
        <div class="d-flex align-items-center">
            <i class="fas fa-check-circle me-3 fa-lg text-pink-600"></i>
            <div class="flex-grow-1">
                <strong class="d-block">Berhasil!</strong>
                {{ session('success') }}
            </div>
        </div>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    @endif

    @if(session('error'))
    <div class="alert alert-soft-pink alert-dismissible fade show shadow-sm" role="alert">
        <div class="d-flex align-items-center">
            <i class="fas fa-exclamation-circle me-3 fa-lg text-danger"></i>
            <div class="flex-grow-1">
                <strong class="d-block">Perhatian!</strong>
                {{ session('error') }}
            </div>
        </div>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    @endif

    <!-- Cart Content -->
    <div class="row">
        <div class="col-12">
            @if(!empty($cart) && count($cart) > 0)
            <form action="{{ route('cart.processPayment') }}" method="POST" id="checkoutForm">
                @csrf
                 
                <div class="card border-0 shadow-lg mb-4">
                    <div class="card-header bg-pink-gradient text-white py-3">
                        <div class="d-flex align-items-center justify-content-between">
                            <div class="d-flex align-items-center">
                                <div class="form-check me-4">
                                    <input class="form-check-input" type="checkbox" id="select-all" 
                                           style="width: 1.2em; height: 1.2em; border: 2px solid #fff;">
                                    <label class="form-check-label text-white fw-medium ms-2" for="select-all">
                                        Pilih Semua
                                    </label>
                                </div>
                                <span class="badge bg-white text-pink-600 px-3 py-2">
                                    <i class="fas fa-box me-1"></i> {{ count($cart) }} Produk
                                </span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-hover align-middle mb-0">
                                <thead class="bg-pink-50">
                                    <tr>
                                        <th width="60" class="ps-4">Pilih</th>
                                        <th>Produk</th>
                                        <th width="150" class="text-center">Harga</th>
                                        <th width="120" class="text-center">Kuantitas</th>
                                        <th width="150" class="text-center">Subtotal</th>
                                        <th width="100" class="text-center">Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($cart as $id => $item)
                                    @php
                                        // AMBIL FOTO LANGSUNG DARI DATABASE (seperti halaman detail)
                                        $produkFromDb = App\Models\Product::with('images')->find($id);
                                        $fotoUrl = null;
                                        
                                        if ($produkFromDb) {
                                            // Cari primary image
                                            $primaryImage = $produkFromDb->images->where('is_primary', true)->first();
                                            if ($primaryImage) {
                                                $fotoUrl = asset('storage/' . $primaryImage->foto);
                                            } 
                                            // Jika tidak ada primary, ambil foto pertama
                                            elseif ($produkFromDb->images->first()) {
                                                $fotoUrl = asset('storage/' . $produkFromDb->images->first()->foto);
                                            }
                                            // Fallback ke kolom foto lama
                                            elseif ($produkFromDb->foto) {
                                                $cleanPath = ltrim($produkFromDb->foto, '/');
                                                $fotoUrl = asset('storage/' . $cleanPath);
                                            }
                                        }
                                        
                                        // Warna placeholder
                                        $colors = ['#ec4899', '#f43f5e', '#8b5cf6', '#06b6d4', '#10b981', '#f59e0b'];
                                        $colorIndex = $id % count($colors);
                                        $bgColor = $colors[$colorIndex];
                                    @endphp
                                    
                                    <tr class="border-bottom border-pink-100 hover-bg-pink-50">
                                        <td class="ps-4">
                                            <div class="form-check">
                                                <input class="form-check-input item-checkbox" type="checkbox" 
                                                       name="selected[]" value="{{ $id }}"
                                                       style="width: 1.2em; height: 1.2em; border-color: #ec4899;"
                                                       {{ ($produkFromDb && $produkFromDb->is_expired) ? 'disabled' : '' }}>
                                            </div>
                                        </td>
                                         <td>
                                            <div class="d-flex align-items-center">
                                                <div class="image-container me-3">
                                                    @if($fotoUrl)
                                                        <img src="{{ $fotoUrl }}" 
                                                             alt="{{ $item['nama'] }}" 
                                                             class="product-image"
                                                             loading="lazy"
                                                             onerror="this.onerror=null; this.style.display='none'; this.parentNode.querySelector('.product-placeholder').style.display='flex';">
                                                        <div class="product-placeholder" style="display: none;">
                                                            <i class="fas fa-box-open text-white fa-2x"></i>
                                                        </div>
                                                    @else
                                                        <div class="product-placeholder" style="background: {{ $bgColor }};">
                                                            <i class="fas fa-box-open text-white fa-2x"></i>
                                                        </div>
                                                    @endif
                                                    
                                                    @if(($item['qty'] ?? 1) > 1)
                                                    <span class="image-badge">
                                                        {{ $item['qty'] ?? 1 }}
                                                    </span>
                                                    @endif
                                                </div>
                                                <div>
                                                    <h6 class="mb-1 fw-semibold text-pink-800">
                                                        {{ $item['nama'] }}
                                                    </h6>
                                                    @if($produkFromDb && $produkFromDb->is_expired)
                                                        <div class="badge bg-danger mb-1 pulse-animation">
                                                            <i class="fas fa-calendar-times me-1"></i>KADALUWARSA
                                                        </div>
                                                    @endif
                                                    <small class="text-muted {{ ($produkFromDb && $produkFromDb->is_expired) ? 'd-block' : '' }}">
                                                        <i class="fas fa-hashtag me-1"></i>ID: {{ $id }}
                                                    </small>
                                                </div>
                                            </div>
                                         </td>
                                        <td class="text-center">
                                            <div class="fw-bold text-pink-600">
                                                Rp {{ number_format($item['harga'], 0, ',', '.') }}
                                            </div>
                                         </td>
                                        <td class="text-center">
                                            <div class="quantity-badge">
                                                <span class="badge bg-pink-100 text-pink-800 px-3 py-2 fw-semibold">
                                                    {{ $item['qty'] }}
                                                </span>
                                            </div>
                                         </td>
                                        <td class="text-center">
                                            <div class="fw-bold fs-5 text-pink-700">
                                                Rp {{ number_format($item['harga'] * $item['qty'], 0, ',', '.') }}
                                            </div>
                                         </td>
                                        <td class="text-center">
                                            <form action="{{ route('cart.remove', $id) }}" method="POST" class="d-inline">
                                                @csrf
                                                <button type="submit" class="btn btn-sm btn-soft-pink" 
                                                        onclick="return confirm('Hapus produk dari keranjang?')"
                                                        data-bs-toggle="tooltip" title="Hapus">
                                                    <i class="fas fa-trash-alt"></i>
                                                </button>
                                            </form>
                                         </td>
                                    </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Cart Summary -->
                <div class="row">
                    <div class="col-lg-8">
                        <div class="card border-pink-200 shadow-sm">
                            <div class="card-body">
                                <h5 class="card-title text-pink-800 mb-3">
                                    <i class="fas fa-tags me-2"></i>Catatan Pesanan
                                </h5>
                                <textarea class="form-control border-pink-200" rows="3" 
                                          id="order_note" name="order_note"
                                          placeholder="Tambahkan catatan untuk pesanan ini..."></textarea>
                                <small class="text-muted mt-2 d-block">
                                    <i class="fas fa-info-circle me-1"></i> Catatan akan ditampilkan di struk pembayaran
                                </small>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-4">
                        <div class="card border-pink-200 shadow-sm">
                            <div class="card-header bg-pink-50 py-3">
                                <h5 class="mb-0 text-pink-800">
                                    <i class="fas fa-receipt me-2"></i>Ringkasan Belanja
                                </h5>
                            </div>
                            <div class="card-body">
                                @php
                                    $totalItems = 0;
                                    $totalPrice = 0;
                                    foreach($cart as $item) {
                                        $totalItems += $item['qty'];
                                        $totalPrice += $item['harga'] * $item['qty'];
                                    }
                                @endphp
                                
                                <div class="d-flex justify-content-between mb-2">
                                    <span class="text-muted">Total Item</span>
                                    <span class="fw-semibold">{{ $totalItems }} produk</span>
                                </div>
                                
                                <div class="d-flex justify-content-between mb-2">
                                    <span class="text-muted">Total Harga</span>
                                    <span class="fw-semibold">Rp {{ number_format($totalPrice, 0, ',', '.') }}</span>
                                </div>
                                
                                <div class="d-flex justify-content-between mb-3">
                                    <span class="text-muted">Biaya Layanan</span>
                                    <span class="fw-semibold">Rp 0</span>
                                </div>
                                
                                <hr class="border-pink-200 my-3">
                                
                                <div class="d-flex justify-content-between mb-4">
                                    <span class="fw-bold text-pink-800">Total Bayar</span>
                                    <span class="fw-bold fs-4 text-pink-600">
                                        Rp {{ number_format($totalPrice, 0, ',', '.') }}
                                    </span>
                                </div>
                                
                                <button type="submit" class="btn btn-pink-gradient w-100 py-3 fw-bold shadow-lg" id="checkoutBtn">
                                    <i class="fas fa-cash-register me-2"></i>Proses Checkout
                                </button>
                                
                                <div class="mt-3 text-center">
                                    <small class="text-muted">
                                        <i class="fas fa-lock me-1"></i> Transaksi aman dan terenkripsi
                                    </small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
            @else
            <!-- Empty Cart State -->
            <div class="text-center py-5">
                <div class="empty-cart-icon mb-4">
                    <i class="fas fa-shopping-bag fa-5x text-pink-300 pulse-animation"></i>
                </div>
                <h3 class="text-pink-800 mb-3">Keranjang Belanja Kosong</h3>
                <p class="text-muted mb-4">Yuk, isi keranjang belanja dengan produk favoritmu!</p>
                <a href="{{ route('product.index') }}" class="btn btn-pink-gradient px-5 py-3 fw-bold">
                    <i class="fas fa-store me-2"></i>Mulai Belanja
                </a>
            </div>
            @endif
        </div>
    </div>
</div>

<script>
// Select all checkbox
document.getElementById('select-all')?.addEventListener('change', function() {
    const checkboxes = document.querySelectorAll('.item-checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.checked = this.checked;
    });
});

// Update select all checkbox state when individual checkboxes change
document.querySelectorAll('.item-checkbox').forEach(checkbox => {
    checkbox.addEventListener('change', function() {
        const checkboxes = document.querySelectorAll('.item-checkbox');
        const selectAll = document.getElementById('select-all');
        
        if (checkboxes.length === 0) return;
        
        const allChecked = Array.from(checkboxes).every(cb => cb.checked);
        if (selectAll) selectAll.checked = allChecked;
    });
});

document.getElementById('checkoutForm')?.addEventListener('submit', async function(e) {
    e.preventDefault();

    const checked = document.querySelectorAll('.item-checkbox:checked');
    if (checked.length === 0) {
        Swal.fire({
            icon: 'warning',
            title: 'Pilih Produk',
            text: 'Silakan pilih minimal 1 produk untuk checkout!',
            confirmButtonColor: '#ec4899',
        });
        return;
    }

    const submitBtn = document.getElementById('checkoutBtn');
    const originalText = submitBtn.innerHTML;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Memproses...';
    submitBtn.disabled = true;

    const formData = new FormData(this);

    try {
        const response = await fetch("{{ route('cart.processPayment') }}", {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Accept': 'application/json',
            },
            body: formData,
        });

        const data = await response.json();

        if (data.error) {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: data.error,
                confirmButtonColor: '#ec4899',
            });
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
            return;
        }

        // Redirect ke halaman pilih kurir (penjualan.create)
        if (data.redirect) {
            window.location.href = data.redirect;
            return;
        }

    } catch (err) {
        console.error(err);
        Swal.fire({
            icon: 'error',
            title: 'Koneksi Error',
            text: 'Terjadi kesalahan koneksi. Silakan coba lagi.',
            confirmButtonColor: '#ec4899',
        });
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
    }
});

// Initialize tooltips
document.addEventListener('DOMContentLoaded', function() {
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.forEach(function(tooltipTriggerEl) {
        new bootstrap.Tooltip(tooltipTriggerEl);
    });
});
</script>

<!-- SweetAlert2 CDN -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!-- Midtrans Snap -->
<script src="https://app.sandbox.midtrans.com/snap/snap.js" data-client-key="{{ config('services.midtrans.clientKey') }}"></script>
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
@endsection