@extends('layout.temp')

@section('title', 'Keranjang Belanja - ' . ($shop_settings['shop_name'] ?? 'PrintPro'))

@section('styles')
<style>
    :root {
        --c-primary: #2563eb;
        --c-slate-950: #020617;
        --c-slate-900: #0f172a;
        --c-slate-800: #1e293b;
        --c-slate-700: #334155;
        --c-slate-600: #475569;
        --c-slate-400: #94a3b8;
        --c-slate-100: #f1f5f9;
        --c-radius: 32px;
        --c-transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1);
    }

    body {
        background: #f8fafc;
        font-family: 'Plus Jakarta Sans', sans-serif;
    }

    .cart-wrapper {
        padding: 60px 0 120px;
        background: radial-gradient(circle at top right, rgba(37, 99, 235, 0.05), transparent 400px);
    }

    .cart-header {
        margin-bottom: 50px;
    }

    .cart-header-title {
        font-size: 3rem;
        font-weight: 950;
        color: var(--c-slate-950);
        letter-spacing: -3px;
        margin-bottom: 10px;
    }

    .cart-header-subtitle {
        color: var(--c-slate-500);
        font-weight: 500;
        font-size: 1.1rem;
    }

    /* Cart Items Area */
    .cart-bulk-action {
        background: white;
        border-radius: 24px;
        padding: 20px 30px;
        border: 1px solid var(--c-slate-100);
        margin-bottom: 25px;
        display: flex;
        align-items: center;
        box-shadow: 0 10px 30px rgba(15, 23, 42, 0.03);
    }

    .cart-item-card {
        background: white;
        border-radius: var(--c-radius);
        border: 1px solid var(--c-slate-100);
        margin-bottom: 20px;
        transition: var(--c-transition);
        overflow: hidden;
        position: relative;
    }

    .cart-item-card:hover {
        box-shadow: 0 30px 60px rgba(15, 23, 42, 0.08);
        transform: translateY(-5px);
        border-color: rgba(37, 99, 235, 0.2);
    }

    .cart-item-body {
        padding: 30px;
    }

    .check-custom {
        width: 24px;
        height: 24px;
        border-radius: 8px;
        border: 2px solid #cbd5e1;
        cursor: pointer;
        transition: 0.2s;
    }

    .check-custom:checked {
        background-color: var(--c-primary);
        border-color: var(--c-primary);
        box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.1);
    }

    .item-img-container {
        width: 120px;
        height: 120px;
        background: #fcfcfc;
        border-radius: 24px;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 15px;
        border: 1px solid var(--c-slate-100);
        transition: 0.3s;
    }

    .cart-item-card:hover .item-img-container {
        background: white;
        transform: scale(1.05);
    }

    .item-img-container img {
        max-width: 100%;
        max-height: 100%;
        object-fit: contain;
    }

    .item-name {
        font-weight: 900;
        color: var(--c-slate-950);
        font-size: 1.25rem;
        margin-bottom: 5px;
        display: block;
        text-decoration: none;
        letter-spacing: -0.5px;
        transition: 0.3s;
    }

    .item-name:hover { color: var(--c-primary); }

    .item-category {
        font-size: 0.75rem;
        font-weight: 800;
        color: var(--c-slate-400);
        text-transform: uppercase;
        letter-spacing: 1.5px;
        background: var(--c-slate-50);
        padding: 4px 10px;
        border-radius: 6px;
        display: inline-block;
        margin-bottom: 20px;
    }

    .item-price-unit {
        font-weight: 950;
        color: var(--c-slate-950);
        font-size: 1.2rem;
        letter-spacing: -0.5px;
    }

    /* Qty Controls */
    .qty-control {
        display: flex;
        align-items: center;
        background: var(--c-slate-100);
        border-radius: 18px;
        padding: 6px;
        width: fit-content;
    }

    .btn-qty-action {
        width: 36px;
        height: 36px;
        border-radius: 14px;
        border: none;
        background: white;
        color: var(--c-slate-950);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 16px;
        transition: 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        box-shadow: 0 4px 10px rgba(0,0,0,0.05);
    }

    .btn-qty-action:hover {
        background: var(--c-primary);
        color: white;
        transform: scale(1.1);
    }

    .qty-display {
        width: 60px;
        border: none;
        background: transparent;
        text-align: center;
        font-weight: 900;
        color: var(--c-slate-950);
        font-size: 1.1rem;
    }

    .btn-delete-pro {
        color: var(--c-slate-400);
        transition: 0.3s;
        border: none;
        background: rgba(239, 68, 68, 0.05);
        width: 45px;
        height: 45px;
        border-radius: 14px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.2rem;
    }

    .btn-delete-pro:hover {
        color: white;
        background: #ef4444;
        transform: rotate(10deg);
    }

    /* Summary Sidebar */
    .cart-summary-card {
        background: var(--c-slate-950);
        border-radius: var(--c-radius);
        padding: 45px;
        color: white;
        position: sticky;
        top: 120px;
        box-shadow: 0 40px 100px rgba(15, 23, 42, 0.2);
    }

    .summary-title {
        font-size: 1.6rem;
        font-weight: 900;
        margin-bottom: 30px;
        padding-bottom: 20px;
        border-bottom: 1px solid rgba(255,255,255,0.08);
        letter-spacing: -1px;
    }

    .sum-row {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;
        color: var(--c-slate-400);
        font-weight: 600;
        font-size: 1rem;
    }

    .total-highlight {
        margin-top: 30px;
        padding-top: 30px;
        border-top: 1px solid rgba(255,255,255,0.08);
    }

    .total-label {
        font-size: 0.75rem;
        font-weight: 800;
        color: var(--c-slate-500);
        text-transform: uppercase;
        letter-spacing: 2px;
        margin-bottom: 8px;
        display: block;
    }

    .total-val {
        font-size: 2.5rem;
        font-weight: 950;
        color: white;
        letter-spacing: -2px;
        line-height: 1;
    }

    .btn-checkout-pro {
        width: 100%;
        height: 75px;
        background: var(--c-primary);
        color: white;
        border-radius: 22px;
        border: none;
        font-weight: 900;
        font-size: 1.15rem;
        margin-top: 40px;
        transition: var(--c-transition);
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 12px;
        box-shadow: 0 15px 30px rgba(37, 99, 235, 0.3);
    }

    .btn-checkout-pro:hover:not(:disabled) {
        transform: translateY(-8px);
        box-shadow: 0 25px 50px rgba(37, 99, 235, 0.5);
        background: #3b82f6;
    }

    .btn-checkout-pro:disabled {
        opacity: 0.3;
        cursor: not-allowed;
        box-shadow: none;
    }

    /* Empty State */
    .cart-empty {
        text-align: center;
        padding: 120px 40px;
        background: white;
        border-radius: var(--c-radius);
        border: 1px solid var(--c-slate-100);
        box-shadow: var(--c-shadow-premium);
    }

    .empty-icon-pro {
        font-size: 100px;
        color: var(--c-primary);
        opacity: 0.15;
        margin-bottom: 30px;
    }

    @media (max-width: 768px) {
        .cart-header-title { font-size: 2.2rem; }
        .item-img-container { width: 100px; height: 100px; }
        .item-name { font-size: 1.1rem; }
        .cart-summary-card { margin-top: 40px; position: static; padding: 30px; }
    }
</style>
@endsection

@section('content')
<div class="cart-wrapper">
    <div class="container animate__animated animate__fadeIn">
        <div class="cart-header">
            <h1 class="cart-header-title">Keranjang Belanja</h1>
            <p class="cart-header-subtitle">Optimalkan produktivitas Anda dengan komponen terbaik.</p>
        </div>

        @if($cart->isEmpty())
            <div class="cart-empty" data-aos="fade-up">
                <i class="lni lni-cart-full empty-icon-pro"></i>
                <h3 class="fw-900 text-slate-900 mb-3" style="font-size: 2rem; letter-spacing: -1px;">Keranjang Kosong</h3>
                <p class="text-muted mb-5 mx-auto" style="max-width: 400px; font-size: 1.1rem;">Sepertinya Anda belum memilih produk. Mari jelajahi katalog suku cadang original kami.</p>
                <a href="/#pricing" class="btn-checkout-pro px-5 d-inline-flex w-auto mx-auto" style="height: 60px;">
                    Mulai Belanja <i class="lni lni-arrow-right"></i>
                </a>
            </div>
        @else
            <form id="checkoutForm" action="{{ route('cart.checkout') }}" method="POST">
                @csrf
                <div class="row g-5">
                    {{-- Left Side: Items --}}
                    <div class="col-lg-8">
                        <div class="cart-bulk-action" data-aos="fade-up">
                            <div class="form-check d-flex align-items-center mb-0">
                                <input class="form-check-input check-custom me-3" type="checkbox" id="checkAll">
                                <label class="form-check-label fw-800 text-dark-900 mt-1" for="checkAll" style="cursor:pointer; font-size: 1.1rem;">
                                    Pilih Semua Item
                                </label>
                            </div>
                        </div>

                        @foreach($cart as $item)
                        <div class="cart-item-card" id="item-row-{{ $item->id }}" data-aos="fade-up" data-aos-delay="{{ $loop->index * 100 }}">
                            <div class="cart-item-body">
                                <div class="row align-items-center g-4">
                                    <div class="col-auto">
                                        <input type="checkbox" class="form-check-input check-custom item-check" 
                                               name="selected_items[]" value="{{ $item->id }}" 
                                               data-subtotal="{{ $item->harga * $item->jumlah }}">
                                    </div>
                                    <div class="col-auto">
                                        <div class="item-img-container">
                                            @if($item->product->image)
                                                <img src="{{ asset('storage/' . $item->product->image) }}" alt="{{ $item->product->name }}">
                                            @else
                                                <i class="lni lni-package text-muted" style="font-size: 2rem;"></i>
                                            @endif
                                        </div>
                                    </div>
                                    <div class="col">
                                        <div class="item-category">{{ $item->product->category->name ?? 'Sparepart' }}</div>
                                        <a href="{{ route('products.show', $item->product->slug) }}" class="item-name">{{ $item->product->name }}</a>
                                        
                                        <div class="d-flex align-items-center justify-content-between mt-4">
                                            <div class="item-price-unit">Rp {{ number_format($item->harga, 0, ',', '.') }}</div>
                                            
                                            <div class="qty-control">
                                                <button type="button" class="btn-qty-action" data-type="decrease" data-id="{{ $item->id }}">
                                                    <i class="lni lni-minus"></i>
                                                </button>
                                                <input type="number" class="qty-display qty-input" value="{{ $item->jumlah }}" data-id="{{ $item->id }}" readonly>
                                                <button type="button" class="btn-qty-action" data-type="increase" data-id="{{ $item->id }}">
                                                    <i class="lni lni-plus"></i>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-auto d-none d-md-block border-start ps-5 ms-3">
                                        <div class="small fw-800 text-muted opacity-50 mb-1 text-uppercase" style="letter-spacing: 1px;">Subtotal</div>
                                        <div class="fw-950 text-slate-900 subtotal-text" style="font-size: 1.4rem; letter-spacing: -1px;">
                                            Rp {{ number_format($item->harga * $item->jumlah, 0, ',', '.') }}
                                        </div>
                                        <div class="text-end mt-4">
                                            <button type="button" class="btn-delete-pro btn-delete-item" data-id="{{ $item->id }}">
                                                <i class="lni lni-trash-can"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        @endforeach
                    </div>

                    {{-- Right Side: Summary --}}
                    <div class="col-lg-4">
                        <div class="cart-summary-card" data-aos="fade-left">
                            <h4 class="summary-title">Ringkasan Belanja</h4>
                            
                            <div class="sum-row">
                                <span>Total Item</span>
                                <span id="totalItems">0 Item</span>
                            </div>
                            <div class="sum-row">
                                <span>Total Harga</span>
                                <span id="totalRaw">Rp 0</span>
                            </div>
                            
                            <div class="total-highlight">
                                <span class="total-label">Tagihan Pembayaran</span>
                                <div class="total-val">Rp <span id="totalFinal">0</span></div>
                            </div>

                            <button type="submit" id="btnCheckout" class="btn-checkout-pro" disabled>
                                CHECKOUT <i class="lni lni-arrow-right"></i>
                            </button>
                            
                            <div class="mt-4 pt-4 border-top border-white-10 opacity-50 d-flex flex-column gap-3">
                                <div class="d-flex align-items-center gap-2 small">
                                    <i class="lni lni-shield text-primary"></i> Transaksi Aman & Terenkripsi
                                </div>
                                <div class="d-flex align-items-center gap-2 small">
                                    <i class="lni lni-money-protection text-success"></i> Jaminan Suku Cadang Original
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
            
            {{-- Hidden delete form --}}
            <form id="hiddenDeleteForm" method="POST" style="display:none;">
                @csrf
                @method('DELETE')
            </form>
        @endif
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const totalFinal = document.getElementById('totalFinal');
    const totalRaw = document.getElementById('totalRaw');
    const totalItems = document.getElementById('totalItems');
    const btnCheckout = document.getElementById('btnCheckout');
    const deleteForm = document.getElementById('hiddenDeleteForm');

    function formatIDR(amount) { 
        return new Intl.NumberFormat('id-ID').format(amount); 
    }

    function calculateTotal() {
        let total = 0;
        let itemsCount = 0;
        document.querySelectorAll('.item-check:checked').forEach(checkbox => {
            total += parseInt(checkbox.dataset.subtotal);
            itemsCount++;
        });
        totalFinal.innerText = formatIDR(total);
        totalRaw.innerText = 'Rp ' + formatIDR(total);
        totalItems.innerText = itemsCount + ' Item';
        btnCheckout.disabled = (total === 0);
    }

    function syncDB(itemId, qty, row) {
        fetch(`/cart/update/${itemId}`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}' },
            body: JSON.stringify({ jumlah: qty })
        })
        .then(res => res.json())
        .then(data => {
            const checkbox = row.querySelector('.item-check');
            const subtotalEl = row.querySelector('.subtotal-text');
            if(subtotalEl) subtotalEl.innerText = 'Rp ' + formatIDR(data.subtotal);
            checkbox.dataset.subtotal = data.subtotal;
            calculateTotal();
        });
    }

    // Qty actions
    document.querySelectorAll('.btn-qty-action').forEach(btn => {
        btn.addEventListener('click', function() {
            const row = this.closest('.cart-item-card');
            const input = row.querySelector('.qty-input');
            let val = parseInt(input.value);
            
            if (this.dataset.type === 'increase') {
                val++;
            } else if (val > 1) {
                val--;
            }
            
            input.value = val;
            syncDB(this.dataset.id, val, row);
        });
    });

    // Delete item
    document.querySelectorAll('.btn-delete-item').forEach(btn => {
        btn.addEventListener('click', function() {
            Swal.fire({
                title: 'Hapus Item?',
                text: "Item ini akan dihapus dari keranjang Anda.",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#2563eb',
                cancelButtonColor: '#cbd5e1',
                confirmButtonText: 'YA, HAPUS',
                cancelButtonText: 'BATAL',
                border: 'none',
                background: '#fff',
                color: '#0f172a'
            }).then((result) => {
                if (result.isConfirmed) {
                    const id = this.dataset.id;
                    deleteForm.action = `/cart/remove/${id}`;
                    deleteForm.submit();
                }
            });
        });
    });

    // Selection
    document.querySelectorAll('.item-check, #checkAll').forEach(el => {
        el.addEventListener('change', function() {
            if(this.id === 'checkAll') {
                document.querySelectorAll('.item-check').forEach(c => c.checked = this.checked);
            }
            calculateTotal();
        });
    });
});
</script>
@endsection
