@extends('layouts.admin')
@section('title', 'Edit Pembelian - SI Apotek')

@section('content')
<div class="mb-6 flex justify-between items-center">
    <div class="flex items-center gap-4">
        <a href="{{ route('purchases.index') }}" class="text-gray-500 hover:text-emerald-600 transition">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path></svg>
        </a>
        <h2 class="text-2xl font-semibold text-gray-700">Edit Transaksi Pembelian (Restock)</h2>
    </div>
</div>

@if($errors->any())
<div class="p-4 mb-4 text-sm text-red-700 bg-red-100 rounded-lg">
    <ul class="list-disc pl-5">
        @foreach($errors->all() as $error)
            <li>{{ $error }}</li>
        @endforeach
    </ul>
</div>
@endif

<form action="{{ route('purchases.update', $purchase->id) }}" method="POST" x-data="purchaseForm()">
    @csrf
    @method('PUT')
    <!-- Detail Transaksi -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-100 p-6 mb-6">
        <h3 class="text-lg font-semibold text-gray-700 mb-4 border-b pb-2">Informasi Pembelian</h3>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Supplier <span class="text-red-500">*</span></label>
                <select name="supplier_id" class="w-full px-4 py-2 border rounded-lg focus:ring-emerald-500 focus:border-emerald-500" required>
                    <option value="">-- Pilih Supplier --</option>
                    @foreach($suppliers as $sup)
                    <option value="{{ $sup->id }}" {{ $sup->id == $purchase->supplier_id ? 'selected' : '' }}>{{ $sup->name }}</option>
                    @endforeach
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Tanggal Terima <span class="text-red-500">*</span></label>
                <input type="date" name="date" value="{{ $purchase->date }}" class="w-full px-4 py-2 border rounded-lg focus:ring-emerald-500 focus:border-emerald-500" required>
            </div>
        </div>
    </div>

    <!-- Rincian Obat -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-100 p-6 mb-6">
        <div class="flex justify-between items-center mb-4 border-b pb-2">
            <h3 class="text-lg font-semibold text-gray-700">Daftar Obat Masuk</h3>
            <button type="button" @click="addRow()" class="bg-emerald-100 text-emerald-700 px-3 py-1.5 rounded-lg text-sm font-semibold hover:bg-emerald-200 transition flex items-center gap-1">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                Tambah Baris
            </button>
        </div>

        <div class="overflow-x-auto">
            <table class="w-full whitespace-no-wrap min-w-[800px]">
                <thead>
                    <tr class="text-xs font-semibold tracking-wide text-left text-gray-500 uppercase border-b bg-gray-50">
                        <th class="px-2 py-3 w-1/4">Nama Obat</th>
                        <th class="px-2 py-3 w-24">Qty</th>
                        <th class="px-2 py-3 w-36">Harga Beli/Satuan</th>
                        <th class="px-2 py-3 w-32">Nomor Batch</th>
                        <th class="px-2 py-3 w-36">Expired Date (ED)</th>
                        <th class="px-2 py-3 w-32 text-right">Subtotal</th>
                        <th class="px-2 py-3 w-12 text-center"></th>
                    </tr>
                </thead>
                <tbody class="divide-y" id="item-rows">
                    <template x-for="(row, index) in rows" :key="row.id">
                        <tr>
                            <td class="px-2 py-2">
                                <select :name="'medicine_id['+index+']'" x-model="row.medicine_id" @change="updatePrice(index)" class="w-full px-2 py-1 text-sm border rounded focus:ring-emerald-500" required>
                                    <option value="">Pilih Obat</option>
                                    <template x-for="med in medicinesList">
                                        <option :value="med.id" :selected="med.id == row.medicine_id" x-text="med.name"></option>
                                    </template>
                                </select>
                            </td>
                            <td class="px-2 py-2">
                                <input type="number" :name="'qty['+index+']'" x-model.number="row.qty" @input="calculateTotal()" min="1" class="w-full px-2 py-1 text-sm border rounded text-center focus:ring-emerald-500" required>
                            </td>
                            <td class="px-2 py-2">
                                <input type="number" :name="'purchase_price['+index+']'" x-model.number="row.price" @input="calculateTotal()" class="w-full px-2 py-1 text-sm border rounded text-right focus:ring-emerald-500" required>
                            </td>
                            <td class="px-2 py-2">
                                <input type="text" :name="'batch_number['+index+']'" x-model="row.batch_number" class="w-full px-2 py-1 text-sm border rounded focus:ring-emerald-500" placeholder="Opsional">
                            </td>
                            <td class="px-2 py-2">
                                <input type="date" :name="'expired_date['+index+']'" x-model="row.expired_date" class="w-full px-2 py-1 text-sm border rounded focus:ring-emerald-500" required>
                            </td>
                            <td class="px-2 py-2 text-right font-semibold text-gray-700 align-middle">
                                <span x-text="formatRupiah(row.qty * row.price)"></span>
                            </td>
                            <td class="px-2 py-2 text-center">
                                <button type="button" @click="removeRow(index)" x-show="rows.length > 1" class="text-red-500 hover:text-red-700 bg-red-50 p-1 rounded">
                                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                                </button>
                            </td>
                        </tr>
                    </template>
                </tbody>
            </table>
        </div>
        
        <div class="mt-6 flex justify-end">
            <div class="bg-gray-50 p-4 rounded-lg border border-gray-200 min-w-[300px]">
                <div class="flex justify-between items-center">
                    <span class="font-medium text-gray-600">Total Transaksi:</span>
                    <span class="text-2xl font-bold text-emerald-600" x-text="formatRupiah(grandTotal)"></span>
                </div>
            </div>
        </div>
    </div>

    <div class="flex justify-end gap-3 pb-10">
        <a href="{{ route('purchases.index') }}" class="px-6 py-2.5 text-sm font-medium text-gray-600 bg-white border border-gray-300 rounded-lg shadow-sm hover:bg-gray-50 transition-colors">Batal</a>
        <button type="submit" class="px-6 py-2.5 text-sm font-medium text-white bg-emerald-600 rounded-lg shadow-md hover:bg-emerald-700 transition-colors flex items-center gap-2">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>
            Simpan Transaksi & Update Stok
        </button>
    </div>
</form>

<script>
    function purchaseForm() {
        return {
            medicinesList: @json($medicines),
            rows: @json($purchaseDetails),
            grandTotal: 0,
            
            init() {
                if(this.rows.length === 0) {
                    this.addRow();
                } else {
                    this.calculateTotal();
                }
            },
            
            addRow() {
                this.rows.push({
                    id: Date.now(),
                    medicine_id: '',
                    qty: 1,
                    price: 0,
                    batch_number: '',
                    expired_date: ''
                });
            },
            
            removeRow(index) {
                this.rows.splice(index, 1);
                this.calculateTotal();
            },
            
            updatePrice(index) {
                let med_id = this.rows[index].medicine_id;
                let medicine = this.medicinesList.find(m => m.id == med_id);
                if (medicine) {
                    this.rows[index].price = parseFloat(medicine.purchase_price) || 0;
                } else {
                    this.rows[index].price = 0;
                }
                this.calculateTotal();
            },
            
            calculateTotal() {
                this.grandTotal = this.rows.reduce((sum, row) => sum + (row.qty * row.price), 0);
            },
            
            formatRupiah(number) {
                return new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', maximumFractionDigits: 0 }).format(number);
            }
        }
    }
</script>
@endsection
