@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; }
    }
</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-shopping-cart"></i> Transaksi Pembelian</h1>
                <p>Tambahkan transaksi pembelian baru tanpa mengganggu tampilan laporan.</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="pembelianForm" method="POST" action="/laporan/pembelian">
                @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="row mt-2 mb-3">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="type">🏷️ Jenis Pembelian</label>
                            <select class="form-control" name="type" id="type" onchange="toggleRawMaterial(this.value)" required>
                                <option value="product">Lainnya / Barang Umum</option>
                                <option value="raw_material">Bahan Baku (Otomatis Tambah Stok)</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6" id="raw_material_container" style="display: none;">
                        <div class="form-group">
                            <label for="raw_material_select">🌿 Pilih Bahan Baku</label>
                            <select class="form-control" name="raw_material_id" id="raw_material_id" onchange="updateItemName(this)">
                                <option value="">-- Pilih Bahan Baku --</option>
                                <option value="new">+ Tambah Bahan Baku Baru</option>
                                @foreach($rawMaterials as $rm)
                                    <option value="{{ $rm->id }}" data-name="{{ $rm->name }}" data-unit="{{ $rm->unit }}">{{ $rm->name }} ({{ $rm->unit }})</option>
                                @endforeach
                            </select>
                            <small class="text-danger" id="raw_material_error" style="display: none;">Silakan pilih bahan baku atau tambah yang baru.</small>
                        </div>
                    </div>
                    <div class="col-md-12" id="new_raw_material_container" style="display: none;">
                        <div class="form-group">
                            <label for="new_raw_material_name">🆕 Nama Bahan Baku Baru</label>
                            <input type="text" class="form-control" name="new_raw_material_name" id="new_raw_material_name" placeholder="Misal: Kopi Bubuk">
                        </div>
                    </div>
                    <div class="col-md-12" id="new_raw_material_unit_container" style="display: none;">
                        <div class="form-group">
                            <label for="new_raw_material_unit">📏 Satuan Bahan Baku</label>
                            <select class="form-control" name="new_raw_material_unit" id="new_raw_material_unit">
                                <option value="">-- Pilih Satuan --</option>
                                <option value="Gram">Gram</option>
                                <option value="Kilogram">Kilogram</option>
                                <option value="Mililiter">Mililiter</option>
                                <option value="Liter">Liter</option>
                                <option value="Pcs">Pcs</option>
                                <option value="Botol">Botol</option>
                            </select>
                            <small class="form-text text-warning mt-2"><i class="fas fa-info-circle mr-1"></i>Gunakan satuan terkecil agar mudah dibuat resepnya. Misal beli per Kg, tapi resep butuh <strong>Gram</strong>.</small>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label for="barang">📦 Nama Barang</label>
                    <input type="text" class="form-control" name="item" id="barang" required placeholder="Contoh: Biji Kopi">
                </div>

                <div class="row">
                    <div class="col-md-7">
                        <div class="form-group">
                            <label for="qty_num">🔢 Jumlah & Satuan</label>
                            <div class="input-group">
                                <input type="number" class="form-control" id="qty_num" step="any" placeholder="0">
                                <div class="input-group-append">
                                    <select class="form-control" id="qty_unit" style="border-top-left-radius: 0; border-bottom-left-radius: 0; background-color: #f8f9fa; min-width: 100px;">
                                        <option value="Kg">Kg</option>
                                        <option value="Gram">Gram</option>
                                        <option value="Liter">Liter</option>
                                        <option value="Ml">Ml</option>
                                        <option value="Pcs">Pcs</option>
                                        <option value="Botol">Botol</option>
                                    </select>
                                </div>
                            </div>
                            <input type="hidden" name="quantity" id="quantity_hidden">
                            <small class="form-text text-info" id="rm_qty_hint" style="display: none;"><i class="fas fa-info-circle"></i> Jika beli 1 Kg tapi bahan baku pakai Gram, tulis 1000 dan pilih Gram. Untuk air mineral atau mie instan, pilih <strong>Pcs</strong> atau <strong>Botol</strong>.</small>
                        </div>
                    </div>
                    <div class="col-md-5">
                        <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="1000" min="1000" oninput="if(this.value.startsWith('0')) this.value = this.value.replace(/^0+/, '');" onkeypress="if(this.value.length == 0 && event.key == '0') return false;">
                        </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 qtyNum = document.getElementById('qty_num');
    const qtyUnit = document.getElementById('qty_unit');
    const qtyHidden = document.getElementById('quantity_hidden');
    const form = document.getElementById('pembelianForm');
    const typeSelect = document.getElementById('type');
    const rmContainer = document.getElementById('raw_material_container');
    const rmSelect = document.getElementById('raw_material_id');
    const barangInput = document.getElementById('barang');
    const rmQtyHint = document.getElementById('rm_qty_hint');
    const newRmContainer = document.getElementById('new_raw_material_container');
    const newRmUnitContainer = document.getElementById('new_raw_material_unit_container');
    const newRmNameInput = document.getElementById('new_raw_material_name');
    const newRmUnitSelect = document.getElementById('new_raw_material_unit');

    function updateHiddenQuantity() {
        qtyHidden.value = qtyNum.value + ' ' + qtyUnit.value;
    }

    function toggleRawMaterial(type) {
        if (type === 'raw_material') {
            rmContainer.style.display = 'block';
            rmSelect.required = true;
            barangInput.readOnly = true;
            rmQtyHint.style.display = 'block';
            qtyUnit.disabled = true;
        } else {
            rmContainer.style.display = 'none';
            rmSelect.required = false;
            rmSelect.value = '';
            barangInput.readOnly = false;
            barangInput.value = '';
            rmQtyHint.style.display = 'none';
            qtyUnit.disabled = false;
            newRmContainer.style.display = 'none';
            newRmUnitContainer.style.display = 'none';
            newRmNameInput.required = false;
            newRmUnitSelect.required = false;
        }
    }

    function updateItemName(selectElement) {
        if (selectElement.value === 'new') {
            newRmContainer.style.display = 'block';
            newRmUnitContainer.style.display = 'block';
            newRmNameInput.required = true;
            newRmUnitSelect.required = true;
            barangInput.readOnly = false;
            barangInput.value = '';
            qtyUnit.disabled = false;
        } else if (selectElement.value) {
            newRmContainer.style.display = 'none';
            newRmUnitContainer.style.display = 'none';
            newRmNameInput.required = false;
            newRmUnitSelect.required = false;
            newRmNameInput.value = '';
            newRmUnitSelect.value = '';

            const selectedOption = selectElement.options[selectElement.selectedIndex];
            barangInput.value = selectedOption.getAttribute('data-name');
            const unit = selectedOption.getAttribute('data-unit');
            qtyUnit.disabled = true;
            qtyUnit.value = unit;
            updateHiddenQuantity();
        } else {
            newRmContainer.style.display = 'none';
            newRmUnitContainer.style.display = 'none';
            newRmNameInput.required = false;
            newRmUnitSelect.required = false;
            barangInput.value = '';
            qtyUnit.disabled = false;
        }
    }

    qtyNum.addEventListener('input', updateHiddenQuantity);
    qtyUnit.addEventListener('change', updateHiddenQuantity);
    newRmNameInput.addEventListener('input', function() {
        if (rmSelect.value === 'new') {
            barangInput.value = this.value;
        }
    });
    newRmUnitSelect.addEventListener('change', function() {
        if (rmSelect.value === 'new') {
            qtyUnit.disabled = true;
            qtyUnit.value = this.value;
            updateHiddenQuantity();
        }
    });

    form.addEventListener('submit', function(e) {
        updateHiddenQuantity();

        if (!qtyNum.value || parseFloat(qtyNum.value) <= 0) {
            e.preventDefault();
            alert('Jumlah harus diisi dan lebih dari 0!');
            qtyNum.focus();
            return false;
        }

        const amountInput = document.getElementById('total_price');
        const amountValue = amountInput.value.toString();

        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;
        }

        if (typeSelect.value === 'raw_material' && (!rmSelect.value || rmSelect.value === '')) {
            e.preventDefault();
            document.getElementById('raw_material_error').style.display = 'block';
            return false;
        }

        document.getElementById('raw_material_error').style.display = 'none';
    });
</script>
@endpush
@endsection
