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

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="store_id">Store <span class="text-danger">*</span></label>
                                        <select class="form-control form-control-sm select2 select2-warning" data-dropdown-css-class="select2-warning" name="store_id" id="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 }} ({{ $store->code }})
                                            </option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="document_type">Tipe Dokumen <span class="text-danger">*</span></label>
                                        <select class="form-control form-control-sm select2 select2-warning" data-dropdown-css-class="select2-warning" name="document_type" id="document_type" required>
                                            <option value="">Pilih Tipe Dokumen</option>
                                            @foreach($variables['document_types'] as $key => $label)
                                            <option value="{{ $key }}"
                                                {{ old('document_type', $data->document_type ?? '') == $key ? 'selected' : '' }}>
                                                {{ $label }}
                                            </option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label for="format_pattern">Pola Format <span class="text-danger">*</span></label>
                                        <input type="text"
                                            class="form-control form-control-sm"
                                            id="format_pattern"
                                            name="format_pattern"
                                            value="{{ old('format_pattern', $data->format_pattern ?? '{DOCTYPE}{SEP}{STORE}{SEP}{YY}{MM}{SEP}{NUMBER}') }}"
                                            required>
                                        <small class="form-text text-muted text-sm">
                                            Gunakan placeholder untuk membuat format Anda.
                                            <a href="#" data-toggle="modal" data-target="#placeholdersModal">Lihat Placeholder yang Tersedia</a>
                                        </small>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label for="prefix">Prefix</label>
                                        <input type="text"
                                            class="form-control form-control-sm"
                                            id="prefix"
                                            name="prefix"
                                            value="{{ old('prefix', $data->prefix ?? '') }}"
                                            maxlength="20">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label for="suffix">Suffix</label>
                                        <input type="text"
                                            class="form-control form-control-sm"
                                            id="suffix"
                                            name="suffix"
                                            value="{{ old('suffix', $data->suffix ?? '') }}"
                                            maxlength="20">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label for="separator">Separator</label>
                                        <input type="text"
                                            class="form-control form-control-sm"
                                            id="separator"
                                            name="separator"
                                            value="{{ old('separator', $data->separator ?? '-') }}"
                                            maxlength="5">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label for="number_length">Panjang Nomor <span class="text-danger">*</span></label>
                                        <input type="number"
                                            class="form-control form-control-sm"
                                            id="number_length"
                                            name="number_length"
                                            value="{{ old('number_length', $data->number_length ?? 4) }}"
                                            min="1"
                                            max="10"
                                            required>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="reset_period">Periode Reset <span class="text-danger">*</span></label>
                                        <select class="form-control form-control-sm select2 select2-warning" data-dropdown-css-class="select2-warning" name="reset_period" id="reset_period" required>
                                            @foreach($variables['reset_periods'] as $key => $label)
                                            <option value="{{ $key }}"
                                                {{ old('reset_period', $data->reset_period ?? 'Monthly') == $key ? 'selected' : '' }}>
                                                {{ $label }}
                                            </option>
                                            @endforeach
                                        </select>
                                        <small class="form-text text-muted text-sm">Kapan counter direset kembali ke 0</small>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="current_number">Nomor Saat Ini</label>
                                        <input type="number"
                                            class="form-control form-control-sm"
                                            id="current_number"
                                            name="current_number"
                                            value="{{ old('current_number', $data->current_number ?? 0) }}"
                                            min="0">
                                        <small class="form-text text-muted text-sm">Nilai counter saat ini (biarkan 0 untuk format baru)</small>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <div class="custom-control custom-checkbox">
                                            <input type="checkbox"
                                                class="custom-control-input"
                                                id="is_active"
                                                name="is_active"
                                                value="1"
                                                {{ old('is_active', $data->is_active ?? true) ? 'checked' : '' }}>
                                            <label class="custom-control-label" for="is_active">
                                                Aktif
                                            </label>
                                        </div>
                                        <small class="form-text text-muted text-sm">Centang untuk mengaktifkan format ini</small>
                                    </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">Preview Format</h5>
                                        </div>
                                        <div class="card-body">
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <strong>Preview Nomor Berikutnya:</strong>
                                                    <div id="formatPreview" class="alert alert-info">
                                                        <code id="previewText">Masukkan pola untuk melihat preview</code>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <strong>Contoh Nomor:</strong>
                                                    <div id="sampleNumbers" class="small text-muted text-sm">
                                                        <div>Contoh 1: <span id="sample1">-</span></div>
                                                        <div>Contoh 5: <span id="sample5">-</span></div>
                                                        <div>Contoh 100: <span id="sample100">-</span></div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-12">
                                    <div class="form-group mb-0">
                                        <button type="submit" class="btn btn-sm btn-info">
                                            <i class="fas fa-save"></i>
                                            {{ $data->id ? 'Perbarui' : 'Buat' }} Format
                                        </button>
                                        <a href="{{ route('numbering_formats.index') }}" class="btn btn-sm btn-secondary ml-2">
                                            <i class="fas fa-times"></i> Batal
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Placeholders Modal -->
<div class="modal fade" id="placeholdersModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Placeholder yang Tersedia</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <table class="table table-hover table-sm">
                    <thead>
                        <tr>
                            <th>Placeholder</th>
                            <th>Deskripsi</th>
                            <th>Contoh</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($variables['placeholders'] as $placeholder => $description)
                        <tr>
                            <td><code>{{ $placeholder }}</code></td>
                            <td>{{ $description }}</td>
                            <td>
                                @if($placeholder === '{YYYY}')
                                2024
                                @elseif($placeholder === '{YY}')
                                24
                                @elseif($placeholder === '{MM}')
                                12
                                @elseif($placeholder === '{DD}')
                                24
                                @elseif($placeholder === '{DOCTYPE}')
                                SPB
                                @elseif($placeholder === '{STORE}')
                                STR01
                                @elseif($placeholder === '{NUMBER}')
                                0001
                                @elseif($placeholder === '{PREFIX}')
                                REQ
                                @elseif($placeholder === '{SUFFIX}')
                                END
                                @elseif($placeholder === '{SEP}')
                                -
                                @endif
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>

                <h6>Contoh Pola:</h6>
                <ul class="list-unstyled">
                    @foreach($variables['pattern_examples'] as $pattern => $example)
                    <li>
                        <code>{{ $pattern }}</code> → <strong>{{ $example }}</strong>
                        <button class="btn btn-sm btn-outline-info ml-2" onclick="usePattern('{{ $pattern }}')">Gunakan Ini</button>
                    </li>
                    @endforeach
                </ul>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function() {
        // Update preview when fields change
        $('#format_pattern, #store_id, #document_type, #prefix, #suffix, #separator, #number_length').on('input change', function() {
            updatePreview();
        });

        // Initial preview update
        updatePreview();

        // Form submit with AJAX
        $('#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: 'Format penomoran berhasil disimpan',
                        icon: 'success',
                        confirmButtonText: 'OK'
                    }).then(() => {
                        window.location.href = "{{ route('numbering_formats.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'
                    });
                }
            });
        });
    });

    function updatePreview() {
        var pattern = $('#format_pattern').val();
        var storeId = $('#store_id').val();
        var documentType = $('#document_type').val();
        var prefix = $('#prefix').val();
        var suffix = $('#suffix').val();
        var separator = $('#separator').val();
        var numberLength = $('#number_length').val();

        if (!pattern || !storeId || !documentType) {
            $('#previewText').text('Pilih toko dan tipe dokumen untuk melihat preview');
            return;
        }

        // Get preview for different sample numbers
        [1, 5, 100].forEach(function(sampleNumber) {
            $.get("{{ route('numbering_formats.preview') }}", {
                    pattern: pattern,
                    store_id: storeId,
                    document_type: documentType,
                    prefix: prefix,
                    suffix: suffix,
                    separator: separator,
                    number_length: numberLength,
                    sample_number: sampleNumber
                })
                .done(function(response) {
                    if (sampleNumber === 1) {
                        $('#previewText').text(response.preview);
                    }
                    $('#sample' + sampleNumber).text(response.preview);
                })
                .fail(function() {
                    if (sampleNumber === 1) {
                        $('#previewText').text('Error membuat preview');
                    }
                });
        });
    }

    function usePattern(pattern) {
        $('#format_pattern').val(pattern);
        updatePreview();
        $('#placeholdersModal').modal('hide');
    }
</script>
@endsection