@extends('layouts.app', [
    'pageTitle' => $title,
])

@section('content')
<div class="mx-auto max-w-3xl">
    <!-- Header -->
    <div class="mb-6">
        <a href="{{ route('purchases.index') }}" class="mb-2 inline-flex items-center text-sm text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300">
            <svg class="mr-1 h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
            </svg>
            Kembali
        </a>
        <h2 class="text-xl font-semibold text-gray-800 dark:text-white/90">{{ $title }}</h2>
    </div>

    @include('partials.alerts')

    <div class="rounded-xl border border-gray-200 bg-white p-6 dark:border-gray-800 dark:bg-white/[0.03]">
        <form action="{{ route('purchases.store') }}" method="POST" enctype="multipart/form-data" x-data="purchaseForm()">
            @csrf

            <div class="space-y-5">
                <!-- Material & Type -->
                <div class="grid grid-cols-1 gap-5 sm:grid-cols-2">
                    <div>
                        <x-form.select name="material_id" label="Bahan" required x-model="material_id" @change="updateUnit()">
                            <option value="">Pilih Bahan</option>
                            @foreach($materials as $material)
                                <option value="{{ $material->id }}" data-unit="{{ $material->unit }}" {{ old('material_id') == $material->id ? 'selected' : '' }}>
                                    {{ $material->name }} ({{ $material->unit }})
                                </option>
                            @endforeach
                        </x-form.select>
                    </div>
                    <div>
                        <x-form.select name="type" label="Tipe Pembelian" required x-model="type">
                            @foreach($types as $key => $label)
                                <option value="{{ $key }}" {{ old('type', 'satuan') == $key ? 'selected' : '' }}>{{ $label }}</option>
                            @endforeach
                        </x-form.select>
                    </div>
                </div>

                <!-- Date & Supplier -->
                <div class="grid grid-cols-1 gap-5 sm:grid-cols-2">
                    <div>
                        <x-form.date-picker name="purchase_date" label="Tanggal Pembelian" :defaultDate="old('purchase_date', date('Y-m-d'))" required/>
                    </div>
                    <div>
                        <x-form.select name="supplier_id" label="Supplier (Opsional)" placeholder="Pilih Supplier">
                            @foreach($suppliers as $supplier)
                                <option value="{{ $supplier->id }}" {{ old('supplier_id') == $supplier->id ? 'selected' : '' }}>
                                    {{ $supplier->name }}
                                </option>
                            @endforeach
                        </x-form.select>
                    </div>
                </div>

                <!-- Quantity & Price -->
                <div class="grid grid-cols-1 gap-5 sm:grid-cols-3">
                    <div>
                        <label class="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-400">
                            Jumlah <span class="text-error-500">*</span>
                        </label>
                        <div class="relative flex">
                            <input 
                                type="text" 
                                name="quantity" 
                                x-model="quantity"
                                @input="calculateTotal()"
                                required
                                class="h-11 w-full rounded-l-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 focus:border-brand-300 focus:outline-none focus:ring focus:ring-brand-200 focus:ring-opacity-40 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90 dark:focus:border-brand-800"
                                placeholder="0"
                            >
                            <span x-text="unit" class="inline-flex items-center px-4 text-sm text-gray-500 bg-gray-100 border border-l-0 border-gray-300 rounded-r-lg dark:bg-gray-800 dark:border-gray-700 dark:text-gray-400 min-w-[60px]"></span>
                        </div>
                    </div>
                    <div>
                        <label class="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-400">
                            Harga Satuan (Modal)<span class="text-error-500">*</span>
                        </label>
                        <div class="relative flex">
                            <span class="inline-flex items-center px-4 text-sm text-gray-500 bg-gray-100 border border-r-0 border-gray-300 rounded-l-lg dark:bg-gray-800 dark:border-gray-700 dark:text-gray-400">Rp</span>
                            <input 
                                type="text" 
                                name="unit_price" 
                                x-model="unit_price_display"
                                @input="formatCurrency($event, 'unit_price'); calculateTotal()"
                                required
                                class="h-11 w-full rounded-r-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 focus:border-brand-300 focus:outline-none focus:ring focus:ring-brand-200 focus:ring-opacity-40 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90 dark:focus:border-brand-800"
                                placeholder="0"
                            >
                        </div>
                    </div>
                    <div>
                        <label class="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-400">
                            Total
                        </label>
                        <div class="relative flex">
                            <span class="inline-flex items-center px-4 text-sm text-gray-500 bg-gray-100 border border-r-0 border-gray-300 rounded-l-lg dark:bg-gray-800 dark:border-gray-700 dark:text-gray-400">Rp</span>
                            <input 
                                type="text" 
                                name="total_price" 
                                x-model="total_display"
                                readonly
                                class="h-11 w-full rounded-r-lg border border-gray-300 bg-gray-50 px-4 py-2.5 text-sm font-medium text-gray-800 dark:border-gray-700 dark:bg-gray-800 dark:text-white/90"
                                placeholder="0"
                            >
                        </div>
                    </div>
                </div>

                <!-- Payment Type -->
                <div class="rounded-lg border border-gray-200 p-4 dark:border-gray-700">
                    <label class="mb-3 block text-sm font-medium text-gray-700 dark:text-gray-400">
                        Jenis Pembayaran <span class="text-error-500">*</span>
                    </label>
                    <div class="flex flex-wrap gap-4">
                        <label class="flex items-center gap-2 cursor-pointer">
                            <input type="radio" name="payment_type" value="full" x-model="payment_type" class="h-4 w-4 text-brand-500 border-gray-300 focus:ring-brand-500">
                            <span class="text-sm text-gray-700 dark:text-gray-300">Bayar Lunas</span>
                        </label>
                        <label class="flex items-center gap-2 cursor-pointer">
                            <input type="radio" name="payment_type" value="dp" x-model="payment_type" class="h-4 w-4 text-brand-500 border-gray-300 focus:ring-brand-500">
                            <span class="text-sm text-gray-700 dark:text-gray-300">DP / Sebagian</span>
                        </label>
                    </div>
                    
                    <!-- DP Amount (show only when DP selected) -->
                    <div x-show="payment_type === 'dp'" x-transition class="mt-4">
                        <label class="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-400">
                            Jumlah Pembayaran Awal
                        </label>
                        <div class="relative flex max-w-xs">
                            <span class="inline-flex items-center px-4 text-sm text-gray-500 bg-gray-100 border border-r-0 border-gray-300 rounded-l-lg dark:bg-gray-800 dark:border-gray-700 dark:text-gray-400">Rp</span>
                            <input 
                                type="text" 
                                name="initial_payment" 
                                x-model="initial_payment_display"
                                @input="formatCurrency($event, 'initial_payment')"
                                class="h-11 w-full rounded-r-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 focus:border-brand-300 focus:outline-none focus:ring focus:ring-brand-200 focus:ring-opacity-40 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90 dark:focus:border-brand-800"
                                placeholder="0"
                            >
                        </div>
                        <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">Kosongkan jika belum ada pembayaran</p>
                    </div>
                </div>

                <!-- Payment Method + Proof -->
                <div x-show="payment_type === 'full' || (payment_type === 'dp' && initial_payment > 0)" x-transition>
                    <!-- Metode Pembayaran -->
                    <div class="mb-4">
                        <label class="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-400">
                            Metode Pembayaran <span class="text-error-500">*</span>
                        </label>
                        <select
                            name="payment_method"
                            x-model="payment_method"
                            required
                            class="h-11 w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 focus:border-brand-300 focus:outline-none focus:ring focus:ring-brand-200 focus:ring-opacity-40 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90 dark:focus:border-brand-800"
                        >
                            <option value="cash">Cash</option>
                            <option value="transfer">Bank Transfer</option>
                        </select>
                        <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                            Bank Transfer akan memotong saldo Kas Bank gabungan.
                        </p>
                    </div>

                    <!-- Payment Proof -->
                    <label class="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-400">
                        Bukti Pembayaran (Opsional)
                    </label>
                    <input 
                        type="file" 
                        name="payment_proof" 
                        accept="image/*"
                        class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-medium file:bg-brand-50 file:text-brand-700 hover:file:bg-brand-100 dark:text-gray-400 dark:file:bg-brand-500/20 dark:file:text-brand-400"
                    >
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">Format: JPG, PNG. Maksimal 2MB</p>
                </div>

                <!-- Notes -->
                <div>
                    <x-form.textarea name="notes" label="Catatan" rows="2" placeholder="Catatan tambahan (opsional)">{{ old('notes') }}</x-form.textarea>
                </div>
            </div>

            <div class="mt-6 flex justify-end gap-3">
                <a href="{{ route('purchases.index') }}" class="rounded-lg border border-gray-300 px-4 py-2.5 text-sm font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-600 dark:text-gray-300 dark:hover:bg-gray-800">
                    Batal
                </a>
                <button type="submit" class="rounded-lg bg-brand-500 px-4 py-2.5 text-sm font-medium text-white shadow-theme-xs hover:bg-brand-600">
                    Simpan
                </button>
            </div>
        </form>
    </div>
</div>

<script>
function purchaseForm() {
    return {
        material_id: '{{ old("material_id") }}',
        type: '{{ old("type", "satuan") }}',
        quantity: '{{ old("quantity", "1") }}',
        unit_price: {{ old("unit_price", 0) }},
        unit_price_display: '{{ old("unit_price") ? number_format(old("unit_price"), 0, ",", ".") : "0" }}',
        total: 0,
        total_display: '0',
        unit: 'pcs',
        materialUnit: 'pcs',
        payment_type: '{{ old("payment_type", "full") }}',
        initial_payment: {{ old("initial_payment", 0) }},
        initial_payment_display: '{{ old("initial_payment") ? number_format(old("initial_payment"), 0, ",", ".") : "0" }}',
        payment_method: '{{ old("payment_method", "cash") }}',

        updateUnit() {
            const select = document.querySelector('[name="material_id"]');
            const option = select.options[select.selectedIndex];
            this.materialUnit = option?.dataset.unit || 'pcs';
            this.syncUnit();
        },

        syncUnit() {
            if (this.type === 'meteran') {
                this.unit = 'm';
            } else {
                this.unit = this.materialUnit;
            }
        },

        formatCurrency(event, field) {
            let value = (event.target.value || '').replace(/[^0-9]/g, '');
            this[field] = parseInt(value) || 0;
            this[field + '_display'] = value.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
        },

        calculateTotal() {
            const qty = parseFloat((this.quantity || '0').toString().replace(',', '.')) || 0;
            this.total = qty * this.unit_price;
            this.total_display = Math.round(this.total).toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.');
        },

        init() {
            this.updateUnit();
            this.calculateTotal();
            this.$watch('type', () => this.syncUnit());
        }
    }
}
</script>
@endsection