@php
    $isAdmin = strtolower(auth()->user()->role->role) == 'admin';
    $selectedId = old('location_id', auth()->user()->location_id);
@endphp

{{-- Bootstrap add --}}
<div class="modal fade" id="addModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <form action="{{ route('users.store') }}" id="addForm" method="POST">
            @csrf
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Tambah User</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Tutup"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-lg-12 mb-3">
                            <label for="name" class="form-label">Nama</label>
                            <input type="text" name="name" placeholder="Masukkan nama" id="name"
                                value="{{ old('name') }}" class="form-control @error('name') is-invalid @enderror"
                                required>
                            @error('name')
                                <div class="invalid-feedback">
                                    {{ $message }}
                                </div>
                            @enderror
                        </div>
                        <div class="col-lg-6 mb-3">
                            <label for="tgl_lahir" class="form-label">Tanggal Lahir</label>
                            <input type="date" name="tgl_lahir" id="tgl_lahir" value="{{ old('tgl_lahir') }}"
                                class="form-control @error('tgl_lahir') is-invalid @enderror" required>
                            @error('tgl_lahir')
                                <div class="invalid-feedback">
                                    {{ $message }}
                                </div>
                            @enderror
                        </div>
                        <div class="col-lg-6 mb-3">
                            <label for="nik" class="form-label">NIK</label>
                            <input type="text" name="nik" id="nik" value="{{ old('nik') }}" placeholder="Masukkan NIK"
                                class="form-control only-number @error('nik') is-invalid @enderror" required>
                            @error('nik')
                                <div class="invalid-feedback">
                                    {{ $message }}
                                </div>
                            @enderror
                        </div>
                        <div class="col-lg-6 mb-3">
                            <label for="no_hp" class="form-label">No HP</label>
                            <input type="text" name="no_hp" id="no_hp" value="{{ old('no_hp') }}"
                                placeholder="Masukkan No HP"
                                class="form-control phone-number @error('no_hp') is-invalid @enderror" required>
                            @error('no_hp')
                                <div class="invalid-feedback">
                                    {{ $message }}
                                </div>
                            @enderror
                        </div>
                        <div class="col-lg-6 mb-3">
                            <label for="email" class="form-label">Email</label>
                            <input type="email" name="email" placeholder="Masukkan Email" id="email"
                                value="{{ old('email') }}" class="form-control @error('email') is-invalid @enderror"
                                required>
                            @error('email')
                                <div class="invalid-feedback">
                                    {{ $message }}
                                </div>
                            @enderror
                        </div>
                        <div class="col-lg-6 mb-3">
                            <label for="username" class="form-label">Username</label>
                            <input type="text" name="username" id="username" placeholder="Masukkan username"
                                value="{{ old('username') }}"
                                class="form-control @error('username') is-invalid @enderror" required>
                            @error('username')
                                <div class="invalid-feedback">
                                    {{ $message }}
                                </div>
                            @enderror
                        </div>
                        <div class="col-lg-6 mb-3">
                            <label for="password" class="form-label">Password</label>
                            <input type="password" name="password" placeholder="Masukkan Password" id="password"
                                class="form-control @error('password') is-invalid @enderror" minlength="8" required>
                            @error('password')
                                <div class="invalid-feedback">
                                    {{ $message }}
                                </div>
                            @enderror
                        </div>
                        <div class="col-lg-6 mb-3">
                            <label for="location" class="form-label">Lokasi</label>
                            <select name="location_id" id="location"
                                class="select2 form-control w-100 location @error('location_id') is-invalid @enderror"
                                required>
                                @if ($isAdmin)
                                    @foreach ($location as $loc)
                                        <option value="{{ $loc->id }}" {{ $loc->id == old('location_id') ? 'selected' : '' }}>
                                            {{ $loc->name }}
                                        </option>
                                    @endforeach
                                @else
                                    <option value="{{ auth()->user()->location_id }}" selected>
                                        {{ auth()->user()->location->name }}
                                    </option>
                                @endif
                            </select>
                            @error('location_id')
                                <div class="invalid-feedback d-block">
                                    {{ $message }}
                                </div>
                            @enderror
                        </div>
                        <div class="col-lg-6 mb-3">
                            @php
                                $isAdmin = strtolower(auth()->user()->role->role) === 'admin';
                            @endphp
                            <label for="roles" class="form-label">Roles</label>
                            <select name="role_id" id="roles"
                                class="select2  form-control w-100 roles @error('role_id') is-invalid @enderror"
                                required>
                                @foreach ($roles as $role)
                                    @if ($isAdmin || in_array(strtolower($role->role), ['operator', 'driver']))
                                        <option value="{{ $role->id }}" {{ $role->id == old('role_id', []) ? 'selected' : '' }}>
                                            {{ ucfirst($role->role) }}
                                        </option>
                                    @endif
                                @endforeach
                            </select>
                            @error('role_id')
                                <div class="invalid-feedback d-block">
                                    {{ $message }}
                                </div>
                            @enderror
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Tutup</button>
                    <button type="submit" class="btn btn-primary">Simpan</button>
                </div>
            </div>
        </form>

    </div>
</div>

{{-- Bootstrap edit --}}
<div class="modal fade" id="editModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <form action="{{ route('users.update', ['user' => '__ID__']) }}" method="POST" id="editForm">
            @csrf
            @method('PUT')
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Ubah User</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Tutup"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-lg-12 mb-3">
                            <label for="name_edit" class="form-label">Nama</label>
                            <input type="text" name="name" id="name_edit" placeholder="Masukkan nama"
                                class="form-control @error('name') is-invalid @enderror" required>
                            @error('name')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>

                        <div class="col-lg-6 mb-3">
                            <label for="tgl_lahir_edit" class="form-label">Tanggal Lahir</label>
                            <input type="date" name="tgl_lahir" id="tgl_lahir_edit"
                                class="form-control @error('tgl_lahir') is-invalid @enderror" required>
                            @error('tgl_lahir')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>

                        <div class="col-lg-6 mb-3">
                            <label for="nik_edit" class="form-label">NIK</label>
                            <input type="text" name="nik" id="nik_edit" placeholder="Masukkan NIK"
                                class="form-control only-number @error('nik') is-invalid @enderror" required>
                            @error('nik')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>

                        <div class="col-lg-6 mb-3">
                            <label for="no_hp_edit" class="form-label">No HP</label>
                            <input type="text" name="no_hp" id="no_hp_edit" placeholder="Masukkan No HP"
                                class="form-control phone-number @error('no_hp') is-invalid @enderror" required>
                            @error('no_hp')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>

                        <div class="col-lg-6 mb-3">
                            <label for="email_edit" class="form-label">Email</label>
                            <input type="email" name="email" id="email_edit" placeholder="Masukkan Email"
                                class="form-control @error('email') is-invalid @enderror" required>
                            @error('email')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>

                        <div class="col-lg-6 mb-3">
                            <label for="username_edit" class="form-label">Username</label>
                            <input type="text" name="username" id="username_edit" placeholder="Masukkan username"
                                class="form-control @error('username') is-invalid @enderror" required>
                            @error('username')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>

                        <div class="col-lg-6 mb-3">
                            <label for="password_edit" class="form-label">Password</label>
                            <input type="password" name="password" id="password_edit" placeholder="Masukkan Password"
                                class="form-control @error('password') is-invalid @enderror" minlength="8">
                            <small class="text-muted">Kosongkan jika tidak ingin mengganti password.</small>
                            @error('password')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>

                        <div class="col-lg-6 mb-3">
                            <label for="location_edit" class="form-label">Lokasi</label>
                            <select name="location_id" id="location_edit"
                                class="select2 location form-control w-100 @error('location_id') is-invalid @enderror"
                                required>
                                @if ($isAdmin)
                                    @foreach ($location as $loc)
                                        <option value="{{ $loc->id }}">{{ $loc->name }}</option>
                                    @endforeach
                                @else
                                    <option value="{{ auth()->user()->location_id }}" selected>
                                        {{ auth()->user()->location->name }}
                                    </option>
                                @endif
                            </select>
                            @error('location_id')
                                <div class="invalid-feedback d-block">{{ $message }}</div>
                            @enderror
                        </div>

                        <div class="col-lg-6 mb-3">
                            @php
                                $isAdmin = strtolower(auth()->user()->role->role) === 'admin';
                            @endphp
                            <label for="roles_edit" class="form-label">Roles</label>
                            <select name="role_id" id="roles_edit"
                                class="select2 roles form-control w-100 @error('role_id') is-invalid @enderror"
                                required>
                                @foreach ($roles as $role)
                                    @if ($isAdmin || in_array(strtolower($role->role), ['operator', 'driver']))
                                        <option value="{{ $role->id }}">{{ ucfirst($role->role) }}</option>
                                    @endif
                                @endforeach
                            </select>
                            @error('role_id')
                                <div class="invalid-feedback d-block">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Tutup</button>
                    <button type="submit" class="btn btn-primary">Simpan</button>
                </div>
            </div>
        </form>
    </div>
</div>


@push('extraJS')
    <script>
        $(document).ready(function () {
            // Select2 init
            $('#addModal .select2.roles').select2({
                dropdownParent: $('#addModal'),
                width: '100%',
                allowClear: true,
                theme: "bootstrap",
                placeholder: "Pilih Role"
            });
            $('#addModal .select2.location').select2({
                dropdownParent: $('#addModal'),
                width: '100%',
                allowClear: true,
                theme: "bootstrap",
                placeholder: "Pilih Lokasi"
            });
            $('#editModal .select2.roles').select2({
                dropdownParent: $('#editModal'),
                width: '100%',
                allowClear: true,
                theme: "bootstrap",
                placeholder: "Pilih Role"
            });
            $('#editModal .select2.location').select2({
                dropdownParent: $('#editModal'),
                width: '100%',
                allowClear: true,
                theme: "bootstrap",
                placeholder: "Pilih Lokasi"
            });

            //      $('#addModal .location, #editModal .location').select2({
            //         placeholder: "Pilih lokasi...",
            //         allowClear: true,
            //          dropdownParent: function() {
            //     return $(this).closest('.modal');
            // },
            //         width: '100%'
            //     });

            // $('#addModal .roles, #editModal .roles').select2({
            //     placeholder: "Pilih role...",
            //     allowClear: true,
            //     dropdownParent: $('#editModal'),
            //     width: '100%'
            // });

            // Handle Add Form Submission
            $('#addForm').on('submit', function (e) {
                e.preventDefault();
                let form = $(this);
                let url = form.attr('action');
                let data = form.serialize();

                clearErrors(form);

                $.post(url, data)
                    .done(function () {
                        $('#addModal').modal('hide');
                        form[0].reset();
                        form.find('.select2').val(null).trigger('change');
                        Swal.fire({
                            icon: 'success',
                            title: 'Berhasil!',
                            text: "User berhasil ditambah",
                            timer: 2000,
                            showConfirmButton: false
                        });
                        $('.data-table').DataTable().ajax.reload();
                        // Tambahkan: reload table atau tampilkan notifikasi sukses
                    })
                    .fail(function (xhr) {
                        console.log(xhr);
                        Swal.fire({
                            icon: 'error',
                            title: 'Gagal!',
                            text: "User gagal ditambah",
                            timer: 2000,
                            showConfirmButton: false
                        });
                        handleValidationErrors(xhr, form);
                    });
            });

            // Handle Edit Form Submission
            $('#editForm').on('submit', function (e) {
                e.preventDefault();
                let form = $(this);
                let userId = form.attr('action').replace('__ID__', form.data('id'));
                let data = form.serialize();

                clearErrors(form);

                $.ajax({
                    url: userId,
                    method: 'PUT',
                    data: data,
                }).done(function () {
                    $('#editModal').modal('hide');
                    Swal.fire({
                        icon: 'success',
                        title: 'Berhasil!',
                        text: "User berhasil diubah",
                        timer: 2000,
                        showConfirmButton: false
                    });
                    $('.data-table').DataTable().ajax.reload();
                    // reload table or show success
                }).fail(function (xhr) {
                    console.log(xhr);
                    handleValidationErrors(xhr, form);
                });
            });

            // Utility: Clear old validation
            function clearErrors(form) {
                form.find('.is-invalid').removeClass('is-invalid');
                form.find('.invalid-feedback').remove();
            }

            // Utility: Handle validation from API
            function handleValidationErrors(xhr, form) {
                if (xhr.status === 422) {
                    let errors = xhr.responseJSON.errors;
                    console.log(errors);
                    for (let field in errors) {
                        let input = form.find(`[name="${field}"]`);
                        if (input.length === 0 && field.includes('.')) {
                            // For array fields like roles[0]
                            let nameAttr = field.replace(/\.\d+/, '[]');
                            input = form.find(`[name="${nameAttr}"]`);
                        }
                        input.addClass('is-invalid');
                        input.after(`<div class="invalid-feedback d-block">${errors[field][0]}</div>`);
                    }
                }
            }
        });
    </script>
@endpush
