@extends('layouts/base_view')
@section('title')
{!! $variables['header_routes'] !!}
@endsection
@section('content')
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-12">
                <div class="card card-outline card-warning">
                    <div class="card-header">
                        <h3 class="card-title">{{ $variables['judul'] }}</h3>
                    </div>
                    <div class="card-body">
                        <form id="formID" method="post" action="{{ route('item_conversions.store', ['prm_id' => $data->id]) }}">
                            @csrf

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="raw_material_id" class="font-weight-bold">Item <span class="text-danger">*</span></label>
                                        <select class="form-control form-control-sm select2 select2-warning" data-dropdown-css-class="select2-warning" name="raw_material_id" id="raw_material_id" required>
                                            <option value="">Pilih Item</option>
                                            @foreach($variables['rawMaterials'] as $rawMaterial)
                                            <option value="{{ $rawMaterial->id }}"
                                                {{ old('raw_material_id', $data->raw_material_id ?? '') == $rawMaterial->id ? 'selected' : '' }}>
                                                {{ $rawMaterial->code }} - {{ $rawMaterial->name }}
                                            </option>
                                            @endforeach
                                        </select>
                                    </div>

                                    <div class="form-group">
                                        <label for="uom_utuh" class="font-weight-bold">UOM Utuh <span class="text-danger">*</span></label>
                                        <small class="text-muted text-xs">*(Max 2 karakter, contoh: DS untuk DUS, BX untuk BOX)</small>
                                        <input value="{{ old('uom_utuh', $data->uom_utuh ?? '') }}"
                                            type="text"
                                            class="form-control form-control-sm text-uppercase"
                                            name="uom_utuh"
                                            id="uom_utuh"
                                            required
                                            maxlength="2"
                                            placeholder="DS"
                                            style="text-transform: uppercase;">
                                        <small class="text-info">Otomatis diubah ke huruf besar</small>
                                    </div>

                                    <div class="form-group">
                                        <label for="uom_pakai" class="font-weight-bold">UOM Pakai <span class="text-danger">*</span></label>
                                        <small class="text-muted text-xs">*(Max 2 karakter, contoh: KG, LT, PC)</small>
                                        <input value="{{ old('uom_pakai', $data->uom_pakai ?? '') }}"
                                            type="text"
                                            class="form-control form-control-sm text-uppercase"
                                            name="uom_pakai"
                                            id="uom_pakai"
                                            required
                                            maxlength="2"
                                            placeholder="KG"
                                            style="text-transform: uppercase;">
                                        <small class="text-info">Otomatis diubah ke huruf besar</small>
                                    </div>
                                </div>

                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="conversion_factor" class="font-weight-bold">Faktor Konversi <span class="text-danger">*</span></label>
                                        <small class="text-muted text-xs">*(Berapa banyak UOM Pakai dalam 1 UOM Utuh)</small>
                                        <input value="{{ old('conversion_factor', $data->conversion_factor ?? '') }}" type="number" step="0.0001" class="form-control form-control-sm" name="conversion_factor" id="conversion_factor" required min="0.0001">
                                    </div>

                                    <div class="form-group">
                                        <label for="notes" class="font-weight-bold">Catatan</label>
                                        <small class="text-muted text-xs">*(Catatan tambahan untuk konversi ini)</small>
                                        <textarea class="form-control form-control-sm" name="notes" id="notes" rows="3" maxlength="500">{{ old('notes', $data->notes ?? '') }}</textarea>
                                    </div>

                                    <div class="form-group">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="is_active" id="is_active" value="1" {{ old('is_active', $data->is_active ?? true) ? 'checked' : '' }}>
                                            <label class="form-check-label font-weight-bold" for="is_active">
                                                Aktif - Aktifkan konversi ini
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Preview Section -->
                            <div class="row">
                                <div class="col-12">
                                    <div class="card bg-light">
                                        <div class="card-header">
                                            <h5 class="mb-0">Pratinjau Konversi</h5>
                                        </div>
                                        <div class="card-body">
                                            <div id="conversionPreview" class="text-center">
                                                <span class="text-muted">Isi form untuk melihat pratinjau konversi</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Action Buttons -->
                            <div class="row">
                                <div class="col-12">
                                    <div class="form-group">
                                        <button type="submit" class="btn btn-sm btn-info button-cek-permission" data-permission="item_conversions.store">
                                            <i class="fa fa-save"></i> Simpan
                                        </button>
                                        <a href="{{ route('item_conversions.index') }}" class="btn btn-sm btn-warning" data='back' onclick="return notificationBeforeBack(event, this);">
                                            <i class="fa fa-arrow-left"></i> Kembali
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
    $(document).ready(function() {
        // Update preview when form changes
        function updatePreview() {
            const uomUtuh = $('#uom_utuh').val();
            const uomPakai = $('#uom_pakai').val();
            const factor = $('#conversion_factor').val();

            if (uomUtuh && uomPakai && factor) {
                const preview = `<strong>1 ${uomUtuh} = ${factor} ${uomPakai}</strong>`;
                $('#conversionPreview').html(preview);
            } else {
                $('#conversionPreview').html('<span class="text-muted">Isi form untuk melihat pratinjau konversi</span>');
            }
        }

        $('#uom_utuh, #uom_pakai, #conversion_factor').on('input', updatePreview);
        updatePreview(); // Initial call

        // Auto-uppercase UOM fields as user types
        $('#uom_utuh, #uom_pakai').on('input', function() {
            this.value = this.value.toUpperCase();
        });

        $('#formID').on('submit', function(e) {
            e.preventDefault();

            const form = this;
            const formData = new FormData(form);

            // Show loading
            Swal.fire({
                title: 'Menyimpan...',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });

            $.ajax({
                type: "POST",
                url: $(form).attr('action'),
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    Swal.fire({
                        title: 'Berhasil!',
                        text: 'Konversi item berhasil disimpan',
                        icon: 'success',
                        confirmButtonText: 'OK'
                    }).then(() => {
                        window.location.href = "{{ route('item_conversions.index') }}";
                    });
                },
                error: function(xhr) {
                    let message = 'Terjadi kesalahan';
                    if (xhr.responseJSON && xhr.responseJSON.errors) {
                        const errors = xhr.responseJSON.errors;
                        message = Object.values(errors).flat().join('\n');
                    } else if (xhr.responseJSON && xhr.responseJSON.message) {
                        message = xhr.responseJSON.message;
                    }

                    Swal.fire({
                        title: 'Error!',
                        text: message,
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                }
            });
        });
    });
</script>
@endsection