@extends('layouts.app')

@section('title', 'Tambah Penjualan - Kei\'s Store')

@section('content')
    <div class="container-fluid px-0">
        {{-- Header full width --}}
        <div class="header-full bg-white border-bottom py-3 px-4">
            <div class="d-flex align-items-center justify-content-between">
                <div class="d-flex align-items-center gap-3">
                    <div class="store-logo">
                    </div>

                    <div class="invoice-preview">
                        <span class="badge bg-light text-dark p-3 rounded-4">
                            <i class="bi bi-receipt me-2" style="color: #ff6b95;"></i>
                            INV-{{ date('Ymd') }}{{ rand(100, 999) }}
                        </span>
                    </div>
                </div>
            </div>
        </div>

        {{-- Alert full width --}}
        @if (session('error'))
            <div class="alert-modern alert-danger mx-4 my-3">
                <i class="bi bi-exclamation-triangle-fill me-2"></i>
                {{ session('error') }}
            </div>
        @endif

        @if (session('success'))
            <div class="alert-modern alert-success mx-4 my-3">
                <i class="bi bi-check-circle-fill me-2"></i>
                {{ session('success') }}
            </div>
        @endif

        <form action="{{ route('penjualan.store') }}" method="POST" id="formPenjualan">
            @csrf
            <input type="hidden" name="user_id" value="{{ $user->user_id }}">
            <input type="hidden" name="diskon" id="diskon" value="0">

            {{-- Main Content tanpa padding --}}
            <div class="row g-0">
                {{-- Bagian Kiri: Produk (70%) --}}
                <div class="col-lg-8 bg-light" style="min-height: calc(100vh - 130px);">
                    <div class="p-4">
                        {{-- Search Bar --}}
                        <div class="search-wrapper mb-4">
                            <i class="bi bi-search search-icon"></i>
                            <input type="text" class="form-control search-input" id="searchProduk"
                                placeholder="Cari produk..." style="padding-left: 45px; height: 50px;">
                        </div>

                        {{-- Grid Produk 4 kolom --}}
                        <div class="row g-3" id="produkGrid">
                             @foreach ($produk as $p)
                                    <div class="col-xl-3 col-lg-4 col-md-6">
                                        <div class="product-card {{ ($p->stok <= 0 || $p->is_expired) ? 'opacity-75' : '' }}" 
                                             data-id="{{ $p->produk_id }}"
                                             data-nama="{{ $p->nama_produk }}" 
                                             data-harga="{{ $p->harga }}"
                                             data-stok="{{ $p->stok }}">
                                            
                                            @php
                                                $images = $p->images;
                                                $primaryImage = $images->where('is_primary', true)->first();
                                                $firstImage = $images->first();
                                                $displayImage = $primaryImage ? $primaryImage->foto : ($firstImage ? $firstImage->foto : null);
                                                $allImages = [];
                                                foreach($images as $img) {
                                                    $allImages[] = asset('storage/' . $img->foto);
                                                }
                                            @endphp

                                            {{-- Foto Produk --}}
                                            <div class="product-image-wrapper">
                                                @if ($displayImage && file_exists(public_path('storage/' . $displayImage)))
                                                    <img src="{{ asset('storage/' . $displayImage) }}"
                                                        alt="{{ $p->nama_produk }}" 
                                                        class="product-image">
                                                @elseif($p->foto && file_exists(public_path('storage/' . $p->foto)))
                                                    <img src="{{ asset('storage/' . $p->foto) }}"
                                                        alt="{{ $p->nama_produk }}" 
                                                        class="product-image">
                                                @else
                                                    <div class="no-image">
                                                        <i class="bi bi-image"></i>
                                                        <span>No Image</span>
                                                    </div>
                                                @endif

                                                {{-- Badge multiple foto --}}
                                                @if(count($allImages) > 1)
                                                    <span class="photo-count-badge">
                                                        <i class="bi bi-images"></i> {{ count($allImages) }}
                                                    </span>
                                                @endif

                                                {{-- Badge Stok --}}
                                                @if ($p->is_expired)
                                                    <span class="stock-badge bg-danger text-white">Kadaluwarsa</span>
                                                @elseif ($p->stok <= 0)
                                                    <span class="stock-badge stock-low">Stok Habis</span>
                                                @elseif ($p->stok < 10)
                                                    <span class="stock-badge stock-low">Sisa {{ $p->stok }}</span>
                                                @else
                                                    <span class="stock-badge stock-available">Tersedia</span>
                                                @endif
                                            </div>

                                            {{-- Info Produk --}}
                                            <div class="product-info">
                                                <h6 class="product-title">{{ $p->nama_produk }}</h6>
                                                <div class="product-price">Rp {{ number_format($p->harga, 0, ',', '.') }}</div>

                                                @php
                                                    $finalDisplayFoto = $displayImage ? asset('storage/' . $displayImage) : ($p->foto ? asset('storage/' . $p->foto) : asset('images/no-image.png'));
                                                @endphp

                                                @php
                                                    $isDisabled = $p->stok <= 0 || $p->is_expired;
                                                @endphp

                                                <button type="button" 
                                                    class="btn-add-cart {{ $isDisabled ? 'disabled' : '' }}"
                                                    @if ($isDisabled) disabled style="opacity: 0.7; cursor: not-allowed; background: #adb5bd; border-color: #adb5bd;" @endif
                                                    onclick="{{ $isDisabled ? '' : 'tambahKeKeranjang('.$p->produk_id.', \''.addslashes($p->nama_produk).'\', '.$p->harga.', '.$p->stok.', '.json_encode($allImages).', \''.$finalDisplayFoto.'\')' }}">
                                                    <i class="bi {{ $p->is_expired ? 'bi-calendar-x' : ($p->stok <= 0 ? 'bi-x-circle' : 'bi-plus-circle') }}"></i>
                                                    <span>
                                                        @if($p->is_expired) Expired 
                                                        @elseif($p->stok <= 0) Habis 
                                                        @else Tambah 
                                                        @endif
                                                    </span>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                            @endforeach
                        </div>
                    </div>
                </div>

                {{-- Bagian Kanan: Keranjang (30%) --}}
                <div class="col-lg-4 bg-white" style="min-height: calc(100vh - 130px); border-left: 1px solid #edf2f7;">
                    <div class="cart-sidebar h-100 d-flex flex-column">
                        <div class="cart-header p-4 border-bottom">
                            <div class="d-flex align-items-center justify-content-between">
                                <div class="d-flex align-items-center gap-2">
                                    <i class="bi bi-cart3 fs-4" style="color: #ff6b95;"></i>
                                    <h5 class="fw-bold mb-0">Keranjang</h5>
                                </div>
                                <span class="cart-badge" id="cartCount">0</span>
                            </div>
                        </div>

                        <div class="cart-items flex-grow-1 p-4" id="cartItems" style="overflow-y: auto; max-height: 350px;">
                            <div class="empty-cart">
                                <i class="bi bi-bag-x"></i>
                                <p>Keranjang kosong</p>
                                <small>Klik "Tambah" pada produk</small>
                            </div>
                        </div>

                        <div class="cart-summary p-4 border-top bg-white">
                            <div id="hiddenInputsContainer"></div>
                            <input type="hidden" name="total_harga" id="total_harga" value="0">
                            <input type="hidden" name="ongkir" id="ongkir" value="0">

                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 8px; font-weight: 600; font-size: 14px;">
                                    <i class="bi bi-geo-alt" style="color: #ff6b95;"></i> Alamat Pengiriman
                                </label>
                                <textarea class="form-control" style="background: #f8f9fa; border: 2px solid #edf2f7; border-radius: 12px; font-size: 13px; color: #4a5568; resize: none; overflow-y: auto;" rows="2" readonly>{{ $user->full_address ?: 'Alamat belum diatur. Silakan atur di Edit Profile.' }}</textarea>
                            </div>

                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 8px; font-weight: 600; font-size: 14px;">
                                    <i class="bi bi-truck" style="color: #ff6b95;"></i> Kurir / Ekspedisi
                                </label>
                                <select name="kurir" id="kurir_manual" style="width: 100%; padding: 10px; border: 2px solid #edf2f7; border-radius: 12px; font-size: 14px; background: white; cursor: pointer;" required>
                                    <option value="">🚚 Pilih Kurir</option>
                                    <option value="CAE Express" data-ongkir="20000">📦 CAE Express - Rp 20.000</option>
                                    <option value="Caeluxe Delivery" data-ongkir="15000">✨ Caeluxe Delivery - Rp 15.000</option>
                                    <option value="Keifast Express" data-ongkir="20000">⚡ Keifast Express - Rp 20.000</option>
                                    <option value="KeiRush" data-ongkir="15000">🏃 KeiRush - Rp 15.000</option>
                                    <option value="EcaMove" data-ongkir="10000">🚀 EcaMove - Rp 10.000</option>
                                </select>
                            </div>

                            <div class="summary-row mb-2">
                                <span class="text-muted">Subtotal Produk</span>
                                <span class="fw-semibold" id="subtotalCart">Rp 0</span>
                            </div>

                            <div class="summary-row mb-2">
                                <span class="text-muted">Ongkos Kirim</span>
                                <span class="fw-semibold" id="ongkirDisplay">Rp 0</span>
                            </div>

                            <div class="summary-total mb-3">
                                <span class="fw-bold">Total</span>
                                <span class="total-price fw-bold fs-4" id="totalCart">Rp 0</span>
                            </div>

                            <button type="submit" class="btn-proses w-100 mb-2" id="btnSubmit" disabled>
                                <span class="spinner-border spinner-border-sm me-2 d-none" id="loadingSpinner" role="status"></span>
                                <span id="btnText">Checkout</span>
                            </button>
                            <a href="{{ route('penjualan.index') }}" class="btn-batal w-100 text-center d-block">Batal</a>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>

    {{-- Modal Pilih Foto SEDERHANA (tanpa Bootstrap Modal) --}}
    <div id="simpleImagePicker" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); z-index: 99999; justify-content: center; align-items: center;">
        <div style="background: white; border-radius: 20px; max-width: 450px; width: 90%; max-height: 80vh; overflow: auto; padding: 20px;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; border-bottom: 1px solid #edf2f7; padding-bottom: 10px;">
                <h4 style="margin: 0; color: #ff6b95;">
                    <i class="bi bi-images"></i> Pilih Foto Produk
                </h4>
                <button onclick="closeSimplePicker()" style="background: none; border: none; font-size: 28px; cursor: pointer; color: #666;">&times;</button>
            </div>
            <p id="simplePickerProductName" style="color: #666; margin-bottom: 15px;"></p>
            <div id="simpleImageList" style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px;"></div>
        </div>
    </div>

    <style>
        .container-fluid {
            padding-left: 0 !important;
            padding-right: 0 !important;
        }

        .header-full {
            width: 100%;
            background: white;
        }

        .product-card {
            background: white;
            border-radius: 16px;
            overflow: hidden;
            transition: all 0.2s;
            border: 1px solid #edf2f7;
            height: 100%;
            display: flex;
            flex-direction: column;
        }

        .product-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 10px 25px rgba(255, 107, 149, 0.15);
            border-color: #ffe4e8;
        }

        .product-image-wrapper {
            position: relative;
            width: 100%;
            padding-top: 100%;
            background: #f8f9fa;
            overflow: hidden;
        }

        .product-image {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
            object-position: center;
        }

        .no-image {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            color: #adb5bd;
        }

        .no-image i {
            font-size: 2rem;
            margin-bottom: 5px;
        }

        .photo-count-badge {
            position: absolute;
            bottom: 10px;
            right: 10px;
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 4px 8px;
            border-radius: 20px;
            font-size: 0.7rem;
            z-index: 2;
            display: flex;
            align-items: center;
            gap: 4px;
        }

        .stock-badge {
            position: absolute;
            top: 10px;
            right: 10px;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 0.7rem;
            font-weight: 600;
            background: white;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            z-index: 2;
        }

        .stock-low {
            background: #fee9e9;
            color: #e53e3e;
        }

        .stock-available {
            background: #e3f9e5;
            color: #38a169;
        }

        .product-info {
            padding: 15px;
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        .product-title {
            font-size: 0.9rem;
            margin-bottom: 5px;
            color: #2d3436;
            font-weight: 600;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .product-price {
            font-weight: 700;
            color: #ff6b95;
            font-size: 1rem;
            margin-bottom: 12px;
        }

        .btn-add-cart {
            width: 100%;
            padding: 8px;
            border: none;
            background: #ff6b95;
            color: white;
            border-radius: 12px;
            font-weight: 500;
            font-size: 0.85rem;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            transition: all 0.2s;
            cursor: pointer;
            margin-top: auto;
        }

        .btn-add-cart:hover {
            background: #ff4d7d;
            transform: scale(1.02);
        }

        .search-wrapper {
            position: relative;
            max-width: 400px;
        }

        .search-icon {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #a0aec0;
            z-index: 10;
        }

        .search-input {
            border: 2px solid #edf2f7;
            border-radius: 30px;
            padding-left: 45px;
            background: white;
        }

        .search-input:focus {
            border-color: #ff6b95;
            box-shadow: 0 0 0 3px rgba(255, 107, 149, 0.1);
            outline: none;
        }

        .cart-sidebar {
            height: 100%;
            background: white;
        }

        .cart-badge {
            background: #ff6b95;
            color: white;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 600;
        }

        .cart-items {
            background: #fcfcfc;
        }

        .cart-items::-webkit-scrollbar {
            width: 5px;
        }

        .cart-items::-webkit-scrollbar-track {
            background: #f1f1f1;
        }

        .cart-items::-webkit-scrollbar-thumb {
            background: #ffb8c9;
            border-radius: 10px;
        }

        .empty-cart {
            text-align: center;
            padding: 40px 20px;
            color: #a0aec0;
        }

        .empty-cart i {
            font-size: 3rem;
            margin-bottom: 10px;
            color: #e2e8f0;
        }

        .cart-item {
            background: white;
            border-radius: 16px;
            padding: 15px;
            margin-bottom: 12px;
            border: 1px solid #edf2f7;
            animation: slideIn 0.3s;
        }

        .cart-item-image {
            width: 50px;
            height: 50px;
            object-fit: cover;
            border-radius: 8px;
            margin-right: 12px;
        }

        @keyframes slideIn {
            from { opacity: 0; transform: translateX(10px); }
            to { opacity: 1; transform: translateX(0); }
        }

        .cart-item-title {
            font-weight: 600;
            font-size: 0.9rem;
            color: #2d3436;
            margin-bottom: 4px;
        }

        .cart-item-price {
            color: #718096;
            font-size: 0.8rem;
            margin-bottom: 10px;
        }

        .cart-item-actions {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .qty-control {
            display: flex;
            align-items: center;
            gap: 5px;
            background: #f8f9fa;
            border-radius: 30px;
            padding: 2px;
        }

        .qty-btn {
            width: 28px;
            height: 28px;
            border: none;
            background: white;
            border-radius: 30px;
            color: #ff6b95;
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 1px solid #edf2f7;
        }

        .qty-btn:hover {
            background: #ff6b95;
            color: white;
        }

        .qty-input {
            width: 35px;
            text-align: center;
            border: none;
            font-weight: 600;
            background: transparent;
        }

        .item-subtotal {
            font-weight: 700;
            color: #ff6b95;
            font-size: 0.9rem;
        }

        .remove-item {
            color: #f56565;
            background: none;
            border: none;
            cursor: pointer;
            padding: 5px;
        }

        .remove-item:hover {
            color: #e53e3e;
            transform: scale(1.1);
        }

        .summary-row {
            display: flex;
            justify-content: space-between;
            font-size: 0.9rem;
        }

        .summary-total {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-top: 12px;
            border-top: 2px dashed #edf2f7;
        }

        .total-price {
            color: #ff6b95;
        }

        .btn-proses {
            background: linear-gradient(135deg, #ff6b95 0%, #ff8e9e 100%);
            color: white;
            border: none;
            padding: 14px;
            border-radius: 16px;
            font-weight: 600;
            transition: all 0.3s;
            cursor: pointer;
            font-size: 1rem;
        }

        .btn-proses:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(255, 107, 149, 0.3);
        }

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

        .btn-batal {
            background: white;
            color: #718096;
            border: 2px solid #edf2f7;
            padding: 12px;
            border-radius: 16px;
            font-weight: 500;
            text-decoration: none;
            transition: all 0.2s;
            display: block;
            text-align: center;
        }

        .btn-batal:hover {
            border-color: #ff6b95;
            color: #ff6b95;
            background: #fff5f7;
        }

        /* Luxury Pink POS Overhaul */
        .header-full {
            background: linear-gradient(to right, #ffffff, #fff5f8);
            box-shadow: 0 2px 15px rgba(255, 107, 149, 0.05);
        }

        .search-input {
            border: 2px solid #ffe4e8;
            transition: all 0.3s ease;
        }

        .search-input:focus {
            border-color: #ff6b95;
            background: #fff;
            box-shadow: 0 0 15px rgba(255, 107, 149, 0.15);
        }

        .cart-header {
            background: linear-gradient(135deg, #fffcfd 0%, #fff5f8 100%);
            border-bottom: 2px solid #ffe4e8;
        }

        .cart-badge {
            background: linear-gradient(135deg, #ff6b95, #ff4d7d);
            box-shadow: 0 4px 10px rgba(255, 107, 149, 0.3);
        }

        .cart-item {
            border: 1px solid #ffe4e8;
            transition: all 0.3s ease;
        }

        .cart-item:hover {
            border-color: #ff6b95;
            box-shadow: 0 5px 15px rgba(255, 107, 149, 0.08);
            transform: scale(1.01);
        }

        .btn-proses {
            background: linear-gradient(135deg, #ff6b95 0%, #ff4d7d 100%);
            border-radius: 20px;
            font-size: 1.1rem;
            letter-spacing: 0.5px;
            text-transform: uppercase;
        }

        .btn-proses:hover:not(:disabled) {
            box-shadow: 0 8px 25px rgba(255, 107, 149, 0.4);
            filter: brightness(1.05);
        }

        .amount-highlight {
            color: #ff6b95;
            font-family: 'Playfair Display', serif;
        }

        .product-card {
            border: 1px solid #ffe4e8;
            background: #ffffff;
        }

        .btn-add-cart {
            background: linear-gradient(135deg, #ff6b95, #ff8e9e);
            border-radius: 30px;
            height: 42px;
        }

        .image-option {
            cursor: pointer;
            border: 2px solid transparent;
            border-radius: 12px;
            overflow: hidden;
            transition: all 0.2s;
            background: #f8f9fa;
        }

        .image-option:hover {
            transform: scale(1.02);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }

        @media (max-width: 1200px) {
            .col-xl-3 { width: 33.333%; }
        }

        @media (max-width: 992px) {
            .col-lg-4 { width: 50%; }
        }

        @media (max-width: 768px) {
            .col-md-6 { width: 50%; }
        }
    </style>

    <script>
        // ==================== KERANJANG BELANJA ====================
        let keranjang = [];
        let currentOngkir = 0;
        let pendingImageCallback = null;

        // Mapping harga ongkir per kurir
        const ongkirMap = {
            'CAE Express': 20000,
            'Caeluxe Delivery': 15000,
            'Keifast Express': 20000,
            'KeiRush': 15000,
            'EcaMove': 10000
        };

        document.addEventListener('DOMContentLoaded', function() {
            @if (!empty($checkoutCart) && count($checkoutCart) > 0)
                @foreach ($checkoutCart as $id => $item)
                    @php
                        $produkItem = $produk->firstWhere('produk_id', $id);
                        $stok = isset($item['stok']) ? $item['stok'] : ($produkItem ? $produkItem->stok : 0);
                        $nama = isset($item['nama']) ? $item['nama'] : ($produkItem ? $produkItem->nama_produk : 'Produk');
                        $harga = isset($item['harga']) ? $item['harga'] : ($produkItem ? $produkItem->harga : 0);
                        $qty = isset($item['qty']) ? $item['qty'] : 1;
                        $foto = isset($item['foto']) ? $item['foto'] : '';
                        
                        // Konversi ke URL absolut jika berupa path relatif
                        if ($foto && strpos($foto, 'http') !== 0) {
                            $foto = asset('storage/' . $foto);
                        }
                    @endphp
                    addToCartDirect({{ $id }}, '{{ addslashes($nama) }}', {{ $harga }}, {{ $stok }}, '{{ $foto }}');
                    {{-- Set quantity awal --}}
                    if (typeof updateQty === 'function') {
                        setTimeout(() => {
                           const key = `{{ $id }}_{{ $foto ?: 'noimage' }}`;
                           updateQty(key, {{ $qty }});
                        }, 50);
                    }
                @endforeach
            @endif
            
            document.getElementById('searchProduk').addEventListener('input', function(e) {
                const keyword = e.target.value.toLowerCase().trim();
                document.querySelectorAll('.product-card').forEach(card => {
                    const nama = card.dataset.nama.toLowerCase();
                    const parentCol = card.closest('.col-xl-3, .col-lg-4, .col-md-6');
                    if (parentCol) {
                        parentCol.style.display = (keyword === '' || nama.includes(keyword)) ? 'block' : 'none';
                    }
                });
            });

            // Event listener untuk perubahan kurir
            const kurirSelect = document.getElementById('kurir_manual');
            kurirSelect.addEventListener('change', function() {
                const selectedValue = this.value;
                if (selectedValue && ongkirMap[selectedValue]) {
                    currentOngkir = ongkirMap[selectedValue];
                } else {
                    currentOngkir = 0;
                }
                updateTotal();
                updateButtonState();
            });
            
            updateButtonState();
        });

        function showImagePicker(productName, images, callback) {
            pendingImageCallback = callback;
            
            const modal = document.getElementById('simpleImagePicker');
            const productNameEl = document.getElementById('simplePickerProductName');
            const imageListEl = document.getElementById('simpleImageList');
            
            productNameEl.innerHTML = `Produk <strong>${productName}</strong> memiliki ${images.length} foto. Klik foto yang ingin dipilih:`;
            
            imageListEl.innerHTML = '';
            images.forEach((imgUrl, index) => {
                const div = document.createElement('div');
                div.className = 'image-option';
                div.style.cssText = 'cursor: pointer; border: 2px solid transparent; border-radius: 12px; overflow: hidden; transition: all 0.2s; background: #f8f9fa;';
                div.setAttribute('data-url', imgUrl);
                div.innerHTML = `
                    <img src="${imgUrl}" style="width: 100%; height: 120px; object-fit: cover;" onerror="this.src='https://placehold.co/200x200?text=No+Image'">
                    <div style="padding: 8px; text-align: center; background: white; font-size: 12px; font-weight: 500;">Foto ${index + 1}</div>
                `;
                div.onclick = function() {
                    document.querySelectorAll('#simpleImageList .image-option').forEach(opt => {
                        opt.style.borderColor = 'transparent';
                    });
                    div.style.borderColor = '#ff6b95';
                    div.style.boxShadow = '0 0 0 2px rgba(255,107,149,0.3)';
                    
                    if (pendingImageCallback) {
                        pendingImageCallback(imgUrl);
                    }
                    closeSimplePicker();
                };
                imageListEl.appendChild(div);
            });
            
            modal.style.display = 'flex';
        }

        function closeSimplePicker() {
            document.getElementById('simpleImagePicker').style.display = 'none';
            pendingImageCallback = null;
        }

        function tambahKeKeranjang(id, nama, harga, stok, allImagesJson, fallbackImage) {
            let allImages = [];
            if (typeof allImagesJson === 'string') {
                try { allImages = JSON.parse(allImagesJson); } catch(e) { allImages = []; }
            } else if (Array.isArray(allImagesJson)) {
                allImages = allImagesJson;
            }
            
            // Jika ada banyak foto, tampilkan picker, jika tidak gunakan fallback (foto utama)
            if (allImages.length > 1) {
                showImagePicker(nama, allImages, function(selectedImage) {
                    addToCartDirect(id, nama, harga, stok, selectedImage);
                });
            } else {
                addToCartDirect(id, nama, harga, stok, allImages.length > 0 ? allImages[0] : fallbackImage);
            }
        }

        function addToCartDirect(id, nama, harga, stok, imageUrl) {
            const fotoKey = imageUrl || 'noimage';
            const uniqueKey = `${id}_${fotoKey}`;
            
            const existingItemIndex = keranjang.findIndex(item => item.uniqueKey === uniqueKey);
            
            if (existingItemIndex !== -1) {
                const newQty = keranjang[existingItemIndex].qty + 1;
                if (newQty > stok) {
                    alert(`Stok ${nama} (foto terpilih) hanya tersisa ${stok - keranjang[existingItemIndex].qty}`);
                    return;
                }
                keranjang[existingItemIndex].qty = newQty;
            } else {
                keranjang.push({ 
                    uniqueKey: uniqueKey,
                    id: id, 
                    nama: nama, 
                    harga: harga, 
                    stok: stok, 
                    qty: 1, 
                    foto: imageUrl 
                });
            }
            renderKeranjang();
        }

        function updateQty(uniqueKey, newQty) {
            const itemIndex = keranjang.findIndex(i => i.uniqueKey === uniqueKey);
            if (itemIndex === -1) return;
            
            const item = keranjang[itemIndex];
            if (newQty < 1) { 
                hapusDariKeranjang(uniqueKey); 
                return; 
            }
            if (newQty > item.stok) { 
                alert(`Stok ${item.nama} hanya tersisa ${item.stok}`); 
                newQty = item.stok; 
            }
            item.qty = newQty;
            renderKeranjang();
        }

        function hapusDariKeranjang(uniqueKey) {
            keranjang = keranjang.filter(item => item.uniqueKey !== uniqueKey);
            renderKeranjang();
        }

        function renderKeranjang() {
            const cartItems = document.getElementById('cartItems');
            const hiddenContainer = document.getElementById('hiddenInputsContainer');
            const cartCount = document.getElementById('cartCount');

            let totalItem = keranjang.reduce((sum, item) => sum + item.qty, 0);
            cartCount.textContent = totalItem;

            if (keranjang.length === 0) {
                cartItems.innerHTML = `<div class="empty-cart"><i class="bi bi-bag-x"></i><p>Keranjang kosong</p><small>Klik "Tambah" pada produk</small></div>`;
                hiddenContainer.innerHTML = '';
                updateTotal();
                return;
            }

            let cartHtml = '', hiddenHtml = '';
            keranjang.forEach(item => {
                const subtotal = item.harga * item.qty;
                const fotoInfo = item.foto ? `<small style="display: block; font-size: 10px; color: #ff6b95; margin-top: 2px;">📷 Varian foto</small>` : '';
                
                cartHtml += `
                    <div class="cart-item" data-uniquekey="${item.uniqueKey}">
                        <div class="d-flex">
                            ${item.foto ? `<img src="${item.foto}" class="cart-item-image" onerror="this.src='https://placehold.co/50x50?text=No+Image'">` : ''}
                            <div class="flex-grow-1">
                                <div class="d-flex justify-content-between align-items-start mb-2">
                                    <div>
                                        <div class="cart-item-title">${item.nama}</div>
                                        ${fotoInfo}
                                    </div>
                                    <button type="button" class="remove-item" onclick="hapusDariKeranjang('${item.uniqueKey}')"><i class="bi bi-trash3"></i></button>
                                </div>
                                <div class="cart-item-price">Rp ${item.harga.toLocaleString('id-ID')}</div>
                                <div class="cart-item-actions">
                                    <div class="qty-control">
                                        <button type="button" class="qty-btn" onclick="updateQty('${item.uniqueKey}', ${item.qty - 1})">−</button>
                                        <input type="text" class="qty-input" value="${item.qty}" readonly>
                                        <button type="button" class="qty-btn" onclick="updateQty('${item.uniqueKey}', ${item.qty + 1})">+</button>
                                    </div>
                                    <div class="item-subtotal">Rp ${subtotal.toLocaleString('id-ID')}</div>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
                hiddenHtml += `
                    <input type="hidden" name="produk_id[]" value="${item.id}">
                    <input type="hidden" name="qty[]" value="${item.qty}">
                    <input type="hidden" name="foto_produk[]" value="${item.foto || ''}">
                    <input type="hidden" name="unique_key[]" value="${item.uniqueKey}">
                `;
            });
            cartItems.innerHTML = cartHtml;
            hiddenContainer.innerHTML = hiddenHtml;
            updateTotal();
        }

        function updateTotal() {
            let subtotal = keranjang.reduce((sum, item) => sum + (item.harga * item.qty), 0);
            const total = subtotal + currentOngkir;
            
            document.getElementById('subtotalCart').textContent = `Rp ${subtotal.toLocaleString('id-ID')}`;
            document.getElementById('ongkirDisplay').textContent = `Rp ${currentOngkir.toLocaleString('id-ID')}`;
            document.getElementById('totalCart').textContent = `Rp ${total.toLocaleString('id-ID')}`;
            document.getElementById('total_harga').value = total;
            document.getElementById('ongkir').value = currentOngkir;
            updateButtonState();
        }

        function updateButtonState() {
            const btnSubmit = document.getElementById('btnSubmit');
            const kurirSelect = document.getElementById('kurir_manual');
            btnSubmit.disabled = (keranjang.length === 0 || !kurirSelect.value);
        }

        document.getElementById('formPenjualan')?.addEventListener('submit', async function(e) {
            e.preventDefault();
            if (keranjang.length === 0) { alert('Keranjang kosong!'); return; }
            const kurirSelect = document.getElementById('kurir_manual');
            if (!kurirSelect.value) { alert('Silakan pilih kurir terlebih dahulu!'); kurirSelect.focus(); return; }

            const btn = document.getElementById('btnSubmit');
            const spinner = document.getElementById('loadingSpinner');
            const btnText = document.getElementById('btnText');

            btn.disabled = true;
            spinner.classList.remove('d-none');
            btnText.textContent = 'Memproses...';

            const formData = new FormData(this);
            try {
                const response = await fetch("{{ route('penjualan.store') }}", {
                    method: "POST", headers: { 'X-CSRF-TOKEN': "{{ csrf_token() }}", 'Accept': 'application/json' }, body: formData
                });
                const data = await response.json();
                if (data.error) { alert('Error: ' + data.error); btn.disabled = false; spinner.classList.add('d-none'); btnText.textContent = 'Bayar via Midtrans'; return; }
                if (data.snap_token) {
                    window.snap.pay(data.snap_token, {
                        onSuccess: function(result) { window.location.href = "/penjualan/" + data.penjualan_id; },
                        onPending: function(result) { alert('Pembayaran pending! Selesaikan pembayaranmu.'); window.location.href = "/penjualan/" + data.penjualan_id; },
                        onError: function(result) { alert('Pembayaran gagal. Silakan coba lagi.'); btn.disabled = false; spinner.classList.add('d-none'); btnText.textContent = 'Bayar via Midtrans'; },
                        onClose: function() { fetch(`/penjualan/${data.penjualan_id}/cancel`, { method: 'DELETE', headers: { 'X-CSRF-TOKEN': "{{ csrf_token() }}" } }).finally(() => { btn.disabled = false; spinner.classList.add('d-none'); btnText.textContent = 'Bayar via Midtrans'; }); }
                    });
                }
            } catch(err) { alert('Terjadi kesalahan koneksi.'); btn.disabled = false; spinner.classList.add('d-none'); btnText.textContent = 'Bayar via Midtrans'; }
        });
    </script>
@endsection