@extends(auth()->user()->role == 'admin' ? 'layouts.admin' : 'layouts.app')

@section('content')
<style>
    .page-header {
        background: linear-gradient(90deg, #ff8a00 0%, #ff5e00 100%);
        color: white;
        padding: 30px;
        border-radius: 15px;
        margin-top: 20px;
        margin-bottom: 30px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.1);
    }
    .page-header h1 { font-weight: 700; font-size: 2rem; margin-bottom: 5px; display: flex; align-items: center; }
    .page-header h1 i { margin-right: 15px; }
    .page-header p { opacity: 0.9; margin-bottom: 0; }
    .custom-card { border-radius: 15px; border: none; box-shadow: 0 4px 12px rgba(0,0,0,0.05); overflow: hidden; }
    .btn-custom { border-radius: 10px; padding: 8px 20px; font-weight: 600; transition: all 0.3s; }
    .header-btn { background: rgba(255,255,255,0.2); border: 1px solid rgba(255,255,255,0.4); color: white; }
    .header-btn:hover { background: white; color: #ff5e00; }
    @media (max-width: 768px) {
        .page-header { padding: 20px; }
        .page-header .d-flex { flex-direction: column; align-items: flex-start !important; gap: 15px; }
    }
    .autocomplete-wrapper { position: relative; }
    .autocomplete-results { position: absolute; top: 100%; left: 0; right: 0; z-index: 1000; background: white; border: 1px solid #ced4da; border-top: none; border-radius: 0 0 10px 10px; max-height: 200px; overflow-y: auto; display: none; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
    .autocomplete-item { padding: 10px 15px; cursor: pointer; transition: background 0.2s; }
    .autocomplete-item:hover { background-color: #fff3e0; color: #ff5e00; }
    .autocomplete-item.active { background-color: #ff5e00; color: white; }
</style>

<div class="container-fluid px-4">
    <div class="page-header shadow">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <h1><i class="fas fa-cash-register"></i> Transaksi Penjualan</h1>
                <p>Tambahkan transaksi penjualan baru pada halaman terpisah.</p>
            </div>
        </div>
    </div>

    <div class="card custom-card mb-4">
        <div class="card-body p-4">
            @if(session('success'))
                <div class="alert alert-success">{{ session('success') }}</div>
            @endif
            @if($errors->any())
                <div class="alert alert-danger">
                    <ul class="mb-0">
                        @foreach($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif

            <form id="penjualanForm" method="POST" action="/laporan/penjualan">
                @csrf
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="tanggal">📅 Tanggal</label>
                            <input type="date" class="form-control" name="date" id="tanggal" required>
                        </div>
                    </div>
                    @if(false)
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="branch">🏢 Cabang</label>
                            <select class="form-control" name="branch" id="branch" required>
                                @foreach($branches as $branch)
                                    <option value="{{ $branch->name }}">{{ $branch->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    @endif
                </div>

                <div class="form-group">
                    <label for="product_display">🥤 Pilih Produk</label>
                    <div class="autocomplete-wrapper">
                        <input type="text" class="form-control" id="product_display" autocomplete="off" placeholder="Ketik nama produk untuk mencari...">
                        <input type="hidden" name="product_id" id="product_id">
                        <div id="autocomplete-results" class="autocomplete-results"></div>
                    </div>
                </div>

                <div class="form-group">
                    <label for="selling_price">💵 Harga Jual (Rp)</label>
                    <input type="number" class="form-control" id="selling_price" readonly placeholder="0" style="background-color: #e9ecef; cursor: not-allowed;">
                </div>

                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="jumlah">🔢 Jumlah</label>
                            <input type="number" class="form-control" name="quantity" id="jumlah" required placeholder="Contoh: 2">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="total_price">💰 Total Harga (Rp)</label>
                            <input type="number" class="form-control" name="total_price" id="total_price" required placeholder="0" min="1000" readonly style="background-color: #e9ecef; cursor: not-allowed;">
                        </div>
                    </div>
                </div>

                <div class="text-right mt-3">
                    <button type="submit" class="btn btn-success btn-lg">Simpan Transaksi</button>
                </div>
            </form>
        </div>
    </div>
</div>

@push('scripts')
<script>
    const productsData = @json($products);
    const productDisplay = document.getElementById('product_display');
    const productIdInput = document.getElementById('product_id');
    const resultsContainer = document.getElementById('autocomplete-results');
    const form = document.getElementById('penjualanForm');

    function resetAutocomplete() {
        productIdInput.value = '';
        productDisplay.value = '';
        document.getElementById('selling_price').value = '';
        document.getElementById('jumlah').value = '';
        document.getElementById('total_price').value = '';
        resultsContainer.style.display = 'none';
    }

    function calculateTotal() {
        const pId = productIdInput.value;
        const prod = productsData.find(p => p.id == pId);
        const price = prod ? prod.selling_price : 0;
        const qty = document.getElementById('jumlah').value || 0;
        document.getElementById('selling_price').value = price;
        document.getElementById('total_price').value = price * qty;
    }

    document.getElementById('jumlah').addEventListener('input', calculateTotal);

    productDisplay.addEventListener('input', function() {
        const query = this.value.toLowerCase();
        const selectedBranch = document.getElementById('branch') ? document.getElementById('branch').value : '{{ Auth::user()->branch }}';
        const filtered = productsData.filter(p => {
            const matchesName = p.name.toLowerCase().includes(query);
            const matchesBranch = !p.branch || p.branch === selectedBranch;
            return matchesName && matchesBranch;
        });

        resultsContainer.innerHTML = '';
        if (filtered.length > 0) {
            filtered.forEach(p => {
                const div = document.createElement('div');
                div.className = 'autocomplete-item';
                div.innerHTML = `<strong>${p.name}</strong> <span class="badge badge-light float-right">${p.category}</span>`;
                div.addEventListener('click', () => {
                    productDisplay.value = p.name;
                    productIdInput.value = p.id;
                    resultsContainer.style.display = 'none';
                    calculateTotal();
                });
                resultsContainer.appendChild(div);
            });
            resultsContainer.style.display = 'block';
        } else {
            resultsContainer.style.display = 'none';
        }
    });

    document.addEventListener('click', function(e) {
        if (!productDisplay.contains(e.target) && !resultsContainer.contains(e.target)) {
            resultsContainer.style.display = 'none';
        }
    });

    document.getElementById('branch')?.addEventListener('change', resetAutocomplete);

    form.addEventListener('submit', function(e) {
        const amountInput = document.getElementById('total_price');
        const amountValue = amountInput.value.toString();

        if (!productIdInput.value) {
            e.preventDefault();
            alert('Pilih produk terlebih dahulu.');
            productDisplay.focus();
            return false;
        }

        if (amountValue && parseInt(amountValue) < 1000) {
            e.preventDefault();
            alert('Total harga minimal adalah Rp 1.000!');
            amountInput.focus();
            return false;
        }

        if (amountValue && amountValue.startsWith('0')) {
            e.preventDefault();
            alert('Total harga tidak boleh diawali dengan angka 0!');
            amountInput.focus();
            return false;
        }
    });
</script>
@endpush
@endsection
