@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('stores.store', ['prm_id' => $data->id]) }}" enctype="multipart/form-data">
                            @csrf
                            <input type="hidden" name="version" value="{{$data->version}}">
                            <div class="row">
                                <div class="form-group col-md-6">
                                    <label for="code" class="font-weight-bold">Kode Store <span class="text-danger">*</span></label>
                                    <input value="{{ old('code', $data->code ?? '') }}"
                                        type="text"
                                        class="form-control form-control-sm"
                                        name="code"
                                        placeholder="contoh: ST001, BGM001"
                                        maxlength="20"
                                        required
                                        {{ $data->id ? 'readonly' : '' }}>
                                    <small class="form-text text-muted">Kode toko unik (maks 20 karakter)</small>
                                    @if ($errors->has('code'))
                                    <span class="text-danger text-left">{{ $errors->first('code') }}</span>
                                    @endif
                                </div>
                                <div class="form-group col-md-6">
                                    <label for="name" class="font-weight-bold">Nama <span class="text-danger">*</span></label>
                                    <input value="{{ old('name', $data->name ?? '') }}" type="text" class="form-control form-control-sm" name="name" placeholder="" required>
                                    @if ($errors->has('name'))
                                    <span class="text-danger text-left">{{ $errors->first('name') }}</span>
                                    @endif
                                </div>
                                <div class="form-group col-md-6">
                                    <label for="pic" class="font-weight-bold">Penanggung Jawab</label>
                                    <input value="{{ old('pic', $data->pic ?? '') }}" type="text" class="form-control form-control-sm" name="pic" placeholder="" required>
                                    @if ($errors->has('pic'))
                                    <span class="text-danger text-left">{{ $errors->first('pic') }}</span>
                                    @endif
                                </div>
                                <div class="form-group col-md-3">
                                    <label for="pic_phone" class="font-weight-bold">Telepon PJ</label>
                                    <input value="{{ old('pic_phone', $data->pic_phone ?? '') }}" type="text" class="form-control form-control-sm" name="pic_phone" placeholder="" required>
                                    @if ($errors->has('pic_phone'))
                                    <span class="text-danger text-left">{{ $errors->first('pic_phone') }}</span>
                                    @endif
                                </div>
                                <div class="form-group col-md-3">
                                    <label for="pic_email" class="font-weight-bold">Email PJ</label>
                                    <input value="{{ old('pic_email', $data->pic_email ?? '') }}" type="email" class="form-control form-control-sm" name="pic_email" placeholder="" required>
                                    @if ($errors->has('pic_email'))
                                    <span class="text-danger text-left">{{ $errors->first('pic_email') }}</span>
                                    @endif
                                </div>
                                <div class="form-group col-md-6">
                                    <label for="address" class="font-weight-bold">Alamat</label>
                                    <input value="{{ old('address', $data->address ?? '') }}" type="text" class="form-control form-control-sm" name="address" placeholder="" required>
                                    @if ($errors->has('address'))
                                    <span class="text-danger text-left">{{ $errors->first('address') }}</span>
                                    @endif
                                </div>
                            </div>
                            <button type="submit" class="btn btn-info btn-sm button-cek-permission" data-permission="stores.store"><i class="fas fa-save"></i> Simpan</button>
                            <a href="{{ route('stores.index') }}" class="btn btn-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() {
        $("input[name='reminder_balance']").on('input', function(e) {
            $("#lblamount").html('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + formatRupiah($(this).val()));
        });

        $("input[name='reminder_balance']").trigger('input'); //agar ke formating 

        var isSubmitting = false;

        $('#formID').validate({
            rules: {
                code: {
                    required: true,
                    maxlength: 20
                },
                name: {
                    required: true,
                    maxlength: 100
                }
            },
            messages: {
                code: {
                    required: "Kode toko wajib diisi",
                    maxlength: "Kode toko maksimal 20 karakter"
                },
                name: {
                    required: "Nama toko wajib diisi",
                    maxlength: "Nama toko maksimal 100 karakter"
                }
            },
            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'), // Gunakan attribute action dari form
                        data: formData,
                        processData: false, // WAJIB: jangan proses jadi query string
                        contentType: false, // WAJIB: agar browser set multipart/form-data
                        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('stores.show', $data->id) }}";
                                } else {
                                    window.location.href = "{{ route('stores.index') }}";
                                }
                            }
                        });
                    })
                    .fail(function(xhr) {
                        let errorText = "Please contact the relevant team or try again.";

                        // Jika status 422 dan ada errors
                        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>`;
                                }
                            }
                        } // Jika ada pesan error umum (misalnya 403, 500, dsb)
                        else if (xhr.responseJSON && xhr.responseJSON.message) {
                            errorText = xhr.responseJSON.message;
                        }

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

@endsection