@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('target_sisa_malam.store', ['prm_id' => $data->id]) }}" enctype="multipart/form-data">
                            @csrf
                            <div class="row">
                                <div class="form-group col-md-6">
                                    <label for="store_id">Store</label>
                                    <select class="form-control form-control-sm select2 select2-warning" data-dropdown-css-class="select2-warning" name="store_id" required>
                                        <option value="">Pilih Store</option>
                                        @foreach($variables['stores'] as $store)
                                        <option value="{{ $store->id }}" {{ old('store_id', $data->store_id ?? '') == $store->id ? 'selected' : '' }}>
                                            {{ $store->name }}
                                        </option>
                                        @endforeach
                                    </select>
                                    @if ($errors->has('store_id'))
                                    <span class="text-danger text-left">{{ $errors->first('store_id') }}</span>
                                    @endif
                                </div>
                                <div class="form-group col-md-6">
                                    <label for="raw_material_id">Item</label>
                                    <select class="form-control form-control-sm select2 select2-warning" data-dropdown-css-class="select2-warning" name="raw_material_id" required>
                                        <option value="">Pilih Item</option>
                                        @foreach($variables['raw_materials'] as $rawMaterial)
                                        <option value="{{ $rawMaterial->id }}" {{ old('raw_material_id', $data->raw_material_id ?? '') == $rawMaterial->id ? 'selected' : '' }}>
                                            {{ $rawMaterial->code }} - {{ $rawMaterial->name }}
                                        </option>
                                        @endforeach
                                    </select>
                                    @if ($errors->has('raw_material_id'))
                                    <span class="text-danger text-left">{{ $errors->first('raw_material_id') }}</span>
                                    @endif
                                </div>
                                <div class="form-group col-md-6">
                                    <label for="target_qty">Jumlah Target</label>
                                    <input value="{{ old('target_qty', $data->target_qty ?? 0) }}" type="number" step="0.01" min="0" max="999999.99" class="form-control form-control-sm" name="target_qty" placeholder="" required>

                                    @if ($errors->has('target_qty'))
                                    <span class="text-danger text-left">{{ $errors->first('target_qty') }}</span>
                                    @endif
                                </div>
                                <div class="form-group col-md-6">
                                    <label for="status">Status</label>
                                    <select class="form-control form-control-sm select2 select2-warning" data-dropdown-css-class="select2-warning" name="status" required>
                                        <option value="Active" {{ old('status', $data->status ?? 'Active') == 'Active' ? 'selected' : '' }}>Aktif</option>
                                        <option value="Inactive" {{ old('status', $data->status ?? '') == 'Inactive' ? 'selected' : '' }}>Nonaktif</option>
                                    </select>

                                    @if ($errors->has('status'))
                                    <span class="text-danger text-left">{{ $errors->first('status') }}</span>
                                    @endif
                                </div>
                            </div>
                            <button type="submit" class="btn btn-outline-info btn-sm button-cek-permission" data-permission="target_sisa_malam.store"><i class="fas fa-save"></i> Simpan</button>
                            <a href="{{ route('target_sisa_malam.index') }}" class="btn btn-outline-warning btn-sm" data='back' onclick="return notificationBeforeBack(event, this);"><i class="fas fa-arrow-left"></i> Kembali</a>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
<script>
    $(document).ready(function() {
        var isSubmitting = false;

        $('#formID').validate({
            rules: {
                store_id: {
                    required: true
                },
                raw_material_id: {
                    required: true
                },
                target_qty: {
                    required: true,
                    number: true,
                    min: 0,
                    max: 999999.99
                },
                status: {
                    required: true
                }
            },
            messages: {
                store_id: "Silakan pilih toko",
                raw_material_id: "Silakan pilih bahan baku",
                target_qty: {
                    required: "Jumlah target wajib diisi",
                    number: "Silakan masukkan angka yang valid",
                    min: "Jumlah target tidak boleh negatif",
                    max: "Jumlah target tidak boleh melebihi 999999.99"
                },
                status: "Silakan pilih status"
            },
            errorElement: 'span',
            errorPlacement: function(error, element) {
                error.addClass('invalid-feedback');
                element.closest('.form-group').append(error);
            },
            highlight: function(element) {
                $(element).addClass('is-invalid');
            },
            unhighlight: function(element) {
                $(element).removeClass('is-invalid');
            },
            submitHandler: function(form) {
                if (isSubmitting) return false;

                isSubmitting = true;
                $('#loaderkdnknz').show();

                var formData = new FormData(form);

                $.ajax({
                        type: "POST",
                        url: $(form).attr('action'),
                        data: formData,
                        processData: false,
                        contentType: false,
                        dataType: "json",
                    })
                    .done(function(data) {
                        Swal.fire({
                            icon: data[0],
                            text: data[1],
                            showCancelButton: false,
                            confirmButtonColor: '#6c757d',
                            confirmButtonText: 'OK',
                            allowOutsideClick: false
                        }).then((result) => {
                            if (result.isConfirmed && data[0] == 'success') {
                                if ("{{$data->id}}" > 0) {
                                    window.location.href = "{{ route('target_sisa_malam.show', $data->id) }}";
                                } else {
                                    window.location.href = "{{ route('target_sisa_malam.index') }}";
                                }
                            }
                        });
                    })
                    .fail(function(xhr) {
                        let errorText = "Silakan hubungi tim terkait atau coba lagi.";

                        if (xhr.status === 422 && xhr.responseJSON.errors) {
                            const errors = xhr.responseJSON.errors;
                            errorText = '';

                            for (const key in errors) {
                                if (errors.hasOwnProperty(key)) {
                                    errorText += `<strong>${key}</strong> : ${errors[key].join(', ')}<br>`;
                                }
                            }
                        } else if (xhr.responseJSON && xhr.responseJSON.message) {
                            errorText = xhr.responseJSON.message;
                        }

                        Swal.fire({
                            icon: "error",
                            title: "Validasi Gagal",
                            html: errorText,
                            confirmButtonColor: '#6c757d',
                            confirmButtonText: 'OK'
                        });
                    })
                    .always(function() {
                        isSubmitting = false;
                        $('#loaderkdnknz').hide();
                    });
            }
        });
    });
</script>

@endsection