@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('range_dois.store', ['prm_id' => $data->id]) }}">
                            @csrf

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="name" class="font-weight-bold">Nama <span class="text-danger">*</span></label>
                                        <small class="text-muted text-xs">*(Nama kategori DOI (contoh: Kritis, Normal, Overstock))</small>
                                        <input value="{{ old('name', $data->name ?? '') }}" type="text" class="form-control form-control-sm" name="name" id="name" required maxlength="100">
                                    </div>

                                    <div class="form-group">
                                        <label for="min_days" class="font-weight-bold">Hari Minimum <span class="text-danger">*</span></label>
                                        <small class="text-muted text-xs">*(Jumlah hari minimum untuk kategori ini)</small>
                                        <input value="{{ old('min_days', $data->min_days ?? '') }}" type="number" step="0.01" class="form-control form-control-sm" name="min_days" id="min_days" required min="0">
                                    </div>

                                    <div class="form-group">
                                        <label for="max_days" class="font-weight-bold">Hari Maksimum <span class="text-danger">*</span></label>
                                        <small class="text-muted text-xs">*(Jumlah hari maksimum untuk kategori ini (gunakan 999999 untuk tidak terbatas))</small>
                                        <input value="{{ old('max_days', $data->max_days ?? '') }}" type="number" step="0.01" class="form-control form-control-sm" name="max_days" id="max_days" required min="0">
                                    </div>
                                </div>

                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="color_code" class="font-weight-bold">Kode Warna</label>
                                        <small class="text-muted text-xs">*(Warna untuk kategori ini dalam laporan)</small>
                                        <input value="{{ old('color_code', $data->color_code ?? '#6c757d') }}" type="color" class="form-control form-control-sm" name="color_code" id="color_code">
                                    </div>

                                    <div class="form-group">
                                        <label for="description" class="font-weight-bold">Deskripsi</label>
                                        <small class="text-muted text-xs">*(Deskripsi kategori DOI)</small>
                                        <textarea class="form-control form-control-sm" name="description" id="description" rows="3" maxlength="500">{{ old('description', $data->description ?? '') }}</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 rentang 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 Rentang</h5>
                                        </div>
                                        <div class="card-body">
                                            <div id="rangePreview" class="text-center">
                                                <span class="text-muted">Isi form untuk melihat pratinjau rentang</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="range_dois.store">
                                            <i class="fa fa-save"></i> Simpan
                                        </button>
                                        <a href="{{ route('range_dois.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 name = $('#name').val();
            const minDays = $('#min_days').val();
            const maxDays = $('#max_days').val();
            const colorCode = $('#color_code').val();

            if (name && minDays !== '' && maxDays !== '') {
                const rangeText = maxDays == 999999 ? `${minDays}+ hari` : `${minDays} - ${maxDays} hari`;
                const preview = `<span class="badge" style="background-color: ${colorCode}; color: white; font-size: 14px;">${name}</span><br><small>${rangeText}</small>`;
                $('#rangePreview').html(preview);
            } else {
                $('#rangePreview').html('<span class="text-muted">Isi form untuk melihat pratinjau rentang</span>');
            }
        }

        $('#name, #min_days, #max_days, #color_code').on('input', updatePreview);
        updatePreview(); // Initial call

        // Validate max_days >= min_days
        $('#min_days, #max_days').on('input', function() {
            const minDays = parseFloat($('#min_days').val()) || 0;
            const maxDays = parseFloat($('#max_days').val()) || 0;

            if (maxDays < minDays && maxDays !== 0) {
                $('#max_days')[0].setCustomValidity('Hari maksimum harus lebih besar atau sama dengan hari minimum');
            } else {
                $('#max_days')[0].setCustomValidity('');
            }
        });

        $('#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: 'Range DOI berhasil disimpan',
                        icon: 'success',
                        confirmButtonText: 'OK'
                    }).then(() => {
                        window.location.href = "{{ route('range_dois.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