@extends('layouts.app')

@section('title', 'Edit Penjualan')

@section('content')
<div class="container-fluid">
    <h3 class="mb-4">Edit Penjualan</h3>

    {{-- Pesan error --}}
    @if($errors->any())
        <div class="alert alert-danger">
            <ul class="mb-0">
                @foreach($errors->all() as $e)
                    <li>{{ $e }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    {{-- Pesan sukses/error dari session --}}
    @if(session('error'))
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            {{ session('error') }}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    @endif

    <form action="{{ route('penjualan.update', $penjualan->penjualan_id) }}" method="POST" id="formPenjualanEdit">
        @csrf
        @method('PUT')

        <div class="row mb-3">
            {{-- Pelanggan --}}
            <div class="col-md-4">
                <label class="form-label">Pelanggan</label>
                <select name="pelanggan_id" class="form-select" id="pelanggan_id_edit">
                    <option value="">-- Tanpa Pelanggan --</option>
                    @foreach($pelanggan as $pl)
                        <option value="{{ $pl->pelanggan_id }}" 
                            {{ $pl->pelanggan_id == $penjualan->pelanggan_id ? 'selected' : '' }}>
                            {{ $pl->nama_pelanggan }} ({{ ucfirst($pl->status) }})
                        </option>
                    @endforeach
                </select>
            </div>

            {{-- Pengguna/User --}}
            <div class="col-md-4">
                <label class="form-label">Pengguna</label>
                <input type="hidden" name="user_id" value="{{ $penjualan->user_id }}">
                <input type="text" class="form-control" value="{{ $penjualan->user->username ?? 'Pengguna Tidak Diketahui' }}" readonly disabled>
                <small class="text-muted">Pengguna tidak dapat diubah</small>
            </div>

            {{-- Status --}}
            <div class="col-md-4">
                <label class="form-label">Status Penjualan</label>
                @php
                    $statusLabels = [
                        'pending' => 'Menunggu Pembayaran',
                        'paid' => 'Lunas',
                        'processing' => 'Sedang Diproses',
                        'shipped' => 'Dikirim',
                        'delivered' => 'Selesai',
                        'cancelled' => 'Dibatalkan',
                    ];
                    $badgeClasses = [
                        'pending' => 'warning',
                        'paid' => 'success',
                        'processing' => 'info',
                        'shipped' => 'primary',
                        'delivered' => 'secondary',
                        'cancelled' => 'danger',
                    ];
                @endphp
                <div class="alert alert-{{ $badgeClasses[$penjualan->status] ?? 'secondary' }} py-2 mb-0">
                    <strong>Status saat ini:</strong> {{ $statusLabels[$penjualan->status] ?? $penjualan->status }}
                </div>
                <small class="text-muted mt-2 d-block">
                    Status tidak dapat diubah di sini. Gunakan tombol update status di halaman daftar penjualan.
                </small>
            </div>
        </div>

        {{-- Daftar Produk --}}
        <div class="mb-4">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h6 class="mb-0"><i class="fas fa-shopping-basket me-2"></i>Produk yang Dibeli</h6>
                <button type="button" class="btn btn-primary btn-sm" id="addRow">
                    <i class="fas fa-plus me-1"></i>Tambah Produk
                </button>
            </div>

            <div class="table-responsive">
                <table class="table table-bordered" id="tabelProduk">
                    <thead class="table-light">
                        <tr>
                            <th width="40%">Produk</th>
                            <th width="15%">Harga Satuan</th>
                            <th width="15%">Jumlah</th>
                            <th width="20%">Subtotal</th>
                            <th width="10%">Aksi</th>
                        </tr>
                    </thead>
                    <tbody id="produkBody">
                        @if($penjualan->detailPenjualan->count() > 0)
                            @foreach($penjualan->detailPenjualan as $dp)
                            <tr data-qtyAwal="{{ $dp->jumlah }}">
                                <td>
                                    <select name="produk_id[]" class="form-select produk" required>
                                        <option value="">-- Pilih Produk --</option>
                                        @foreach($produk as $p)
                                            <option value="{{ $p->produk_id }}" 
                                                    data-harga="{{ $p->harga }}" 
                                                    data-stok="{{ $p->stok }}" 
                                                    data-kadaluarsa="{{ $p->tanggal_kadaluarsa ?? '' }}"
                                                    {{ $p->produk_id == $dp->produk_id ? 'selected' : '' }}>
                                                {{ $p->nama_produk }} - Rp {{ number_format($p->harga, 0, ',', '.') }} (Stok: {{ $p->stok }})
                                            </option>
                                        @endforeach
                                    </select>
                                </td>
                                <td><input type="text" class="form-control harga" value="{{ number_format($dp->harga_satuan,0,',','.') }}" readonly></td>
                                <td><input type="number" name="jumlah[]" class="form-control jumlah" min="1" value="{{ $dp->jumlah }}" required></td>
                                <td><input type="text" class="form-control subtotal" value="{{ number_format($dp->subtotal,0,',','.') }}" readonly></td>
                                <td class="text-center">
                                    <button type="button" class="btn btn-danger btn-sm removeRow"><i class="fas fa-times"></i></button>
                                </td>
                            </tr>
                            @endforeach
                        @else
                            <tr>
                                <td colspan="5" class="text-center text-muted">Tidak ada produk</td>
                            </tr>
                        @endif
                    </tbody>
                </table>
            </div>
        </div>

        <div class="row">
            <div class="col-md-6">
                <div class="border rounded p-3">
                    <h6><i class="fas fa-receipt me-2"></i>Ringkasan Belanja</h6>
                    <div class="d-flex justify-content-between mb-2">
                        <span>Subtotal Produk:</span>
                        <span id="subtotalDisplay">Rp 0</span>
                    </div>
                    <div class="d-flex justify-content-between mb-2">
                        <span>Total Item:</span>
                        <span id="totalItemDisplay">0 item</span>
                    </div>
                    <div class="d-flex justify-content-between fw-bold fs-5">
                        <span>Total:</span>
                        <span id="totalDisplay">Rp {{ number_format($penjualan->total_harga, 0, ',', '.') }}</span>
                    </div>
                    <input type="hidden" name="total_harga" id="total_harga" value="{{ $penjualan->total_harga }}">
                </div>
            </div>

            <div class="col-md-6">
                <div class="border rounded p-3">
                    <h6><i class="fas fa-credit-card me-2"></i>Informasi Tambahan</h6>
                    <div class="mb-2">
                        <strong>Tanggal Penjualan:</strong><br>
                        {{ \Carbon\Carbon::parse($penjualan->tanggal_penjualan)->format('d/m/Y H:i:s') }}
                    </div>
                    <div class="mb-2">
                        <strong>ID Penjualan:</strong><br>
                        {{ $penjualan->penjualan_id }}
                    </div>
                    <small class="text-muted mt-2 d-block">
                        * Perubahan produk akan mempengaruhi total harga.<br>
                        * Stok akan disesuaikan otomatis.
                    </small>
                </div>
            </div>
        </div>

        {{-- Tombol Aksi --}}
        <div class="text-end mt-4 d-flex justify-content-end gap-2">
            <a href="{{ route('penjualan.index') }}" class="btn btn-secondary">
                <i class="fas fa-arrow-left me-1"></i> Kembali
            </a>
            <button type="submit" class="btn btn-success">
                <i class="fas fa-save me-1"></i> Update Transaksi
            </button>
        </div>
    </form>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const tabelBody = document.querySelector('#produkBody');
    const addRowBtn = document.querySelector('#addRow');
    let stokSementara = {};

    // Inisialisasi stok sementara dari produk yang ada
    document.querySelectorAll('.produk option[data-stok]').forEach(opt => {
        stokSementara[opt.value] = parseInt(opt.dataset.stok);
        const tanggalKadaluarsa = opt.dataset.kadaluarsa;
        if (tanggalKadaluarsa) {
            const today = new Date();
            const kadaluarsa = new Date(tanggalKadaluarsa);
            const diffDays = Math.ceil((kadaluarsa - today) / (1000 * 60 * 60 * 24));
            if (diffDays < 0) {
                opt.disabled = true;
                opt.textContent += ' ❌ Kadaluarsa!';
            } else if (diffDays <= 30) {
                opt.textContent += ` ⚠️ Akan kadaluarsa dalam ${diffDays} hari`;
            }
        }
    });

    function formatRupiah(num) {
        return 'Rp ' + Number(num).toLocaleString('id-ID');
    }

    function hitungTotal() {
        let total = 0;
        let totalItem = 0;
        document.querySelectorAll('#produkBody tr').forEach(tr => {
            const subtotalInput = tr.querySelector('.subtotal');
            if (subtotalInput && subtotalInput.value) {
                const subtotal = parseFloat(subtotalInput.value.replace(/\D/g, '')) || 0;
                const qty = parseInt(tr.querySelector('.jumlah')?.value) || 0;
                total += subtotal;
                totalItem += qty;
            }
        });

        document.querySelector('#subtotalDisplay').textContent = formatRupiah(total);
        document.querySelector('#totalItemDisplay').textContent = totalItem + ' item';
        document.querySelector('#totalDisplay').textContent = formatRupiah(total);
        document.querySelector('#total_harga').value = total;
    }

    // Tambah row
    if (addRowBtn) {
        addRowBtn.addEventListener('click', function () {
            const firstRow = tabelBody.querySelector('tr');
            if (firstRow && firstRow.cells && firstRow.cells.length > 0) {
                const newRow = firstRow.cloneNode(true);
                newRow.querySelectorAll('input').forEach(input => {
                    if (input.classList.contains('jumlah')) {
                        input.value = 1;
                    } else if (!input.classList.contains('subtotal')) {
                        input.value = '';
                    }
                });
                newRow.querySelector('.produk').value = '';
                newRow.querySelector('.harga').value = '';
                newRow.querySelector('.subtotal').value = '';
                newRow.dataset.qtyAwal = '0';
                tabelBody.appendChild(newRow);
                hitungTotal();
            }
        });
    }

    // Hapus row
    tabelBody.addEventListener('click', function (e) {
        if (e.target.closest('.removeRow')) {
            const tr = e.target.closest('tr');
            if (tabelBody.querySelectorAll('tr').length > 1) {
                const select = tr.querySelector('.produk');
                const qty = parseInt(tr.querySelector('.jumlah').value) || 0;
                const produkId = select.value;
                if (produkId) stokSementara[produkId] = (stokSementara[produkId] || 0) + qty;
                tr.remove();
            } else {
                alert('Minimal harus ada 1 produk!');
            }
            hitungTotal();
        }
    });

    // Change produk
    tabelBody.addEventListener('change', function (e) {
        if (e.target.classList.contains('produk')) {
            const selected = e.target.selectedOptions[0];
            const harga = parseFloat(selected.dataset.harga || 0);
            const stok = stokSementara[selected.value] || 0;
            const tr = e.target.closest('tr');
            tr.querySelector('.harga').value = Number(harga).toLocaleString('id-ID');
            const qty = parseInt(tr.querySelector('.jumlah').value) || 1;
            
            if (qty > stok) {
                alert(`⚠️ Stok produk hanya ${stok} tersisa!`);
                tr.querySelector('.jumlah').value = stok;
            }
            tr.querySelector('.subtotal').value = (harga * qty).toLocaleString('id-ID');
            
            // Update stok sementara
            const oldProdukId = tr.dataset.oldProdukId;
            if (oldProdukId && stokSementara[oldProdukId] !== undefined) {
                stokSementara[oldProdukId] += (parseInt(tr.dataset.qtyAwal || 0));
            }
            stokSementara[selected.value] = stok - qty;
            tr.dataset.oldProdukId = selected.value;
            
            hitungTotal();
        }
    });

    // Input jumlah
    tabelBody.addEventListener('input', function (e) {
        if (e.target.classList.contains('jumlah')) {
            const tr = e.target.closest('tr');
            const select = tr.querySelector('.produk');
            const produkId = select.value;
            const harga = parseFloat(select.selectedOptions[0]?.dataset.harga || 0);
            let stok = stokSementara[produkId] || 0;
            let qty = parseInt(e.target.value) || 0;
            
            if (!produkId) return;

            const qtyAwal = parseInt(tr.dataset.qtyAwal || 0);
            
            if (qty > stok + qtyAwal) {
                alert(`⚠️ Jumlah melebihi stok! Sisa stok: ${stok + qtyAwal}`);
                qty = stok + qtyAwal;
                e.target.value = qty;
            }

            stokSementara[produkId] = stok + qtyAwal - qty;
            tr.dataset.qtyAwal = qty;
            
            tr.querySelector('.subtotal').value = (harga * qty).toLocaleString('id-ID');
            hitungTotal();
        }
    });

    // Hitung total awal
    hitungTotal();
});
</script>

<style>
    .table-responsive {
        overflow-x: auto;
    }
    .btn-sm {
        padding: 0.25rem 0.5rem;
        font-size: 0.875rem;
    }
</style>
@endsection