@section('heading', 'User')

@extends('layouts.app')

@section('content')


<style>
    .warning {
        background-color: yellow;
    }

</style>


<!-- Content Header (Page header) -->
<section class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1> Users </h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item">
                        <a href="{{route('home')}}">Dashboard</a>
                    </li>
                    <li class="breadcrumb-item active"> Users </li>
                </ol>
            </div>
        </div>
    </div>
</section>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title"> <b>Users</b> </h3>
                        <div class="card-tools">
                            @can('users.create')
                                <button type="button" class="btn btn-success text-white btn-sm m-1" title="Tambah" data-toggle="modal" data-target="#modal-tambah">
                                    <i class="fas fa-plus-circle"></i> Tambah
                                </button>
                                <div class="modal fade" id="modal-tambah">
                                    <div class="modal-dialog modal-xl">
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <h4 class="modal-title"> Tambah User </h4>
                                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                    <span aria-hidden="true">&times;</span>
                                                </button>
                                            </div>
                                            <form action="{{ route('user.save') }}" method="POST" enctype="multipart/form-data" id="form-tambah-user">
                                                @csrf
                                                <div class="modal-body">
                                                    <div class="form-group">
                                                        <label>Nama User <span class="text-danger">*</span> </label>
                                                        <input type="text" name="name" id="name-tambah" value="{{ old('name') }}" placeholder="Masukkan Nama User" class="form-control @error('name') is-invalid @enderror" required>
                                                        @error('name')
                                                        <div class="invalid-feedback" style="display: block">
                                                            {{ $message }}
                                                        </div>
                                                        @enderror
                                                    </div>
                                                    <div class="form-group">
                                                        <label>Email <span class="text-danger">*</span> </label>
                                                        <input type="email" name="email" id="email-tambah"  value="{{ old('email') }}" placeholder="Masukkan Email" class="form-control @error('email') is-invalid @enderror" required>
                                                        @error('email')
                                                        <div class="invalid-feedback" style="display: block">
                                                            {{ $message }}
                                                        </div>
                                                        @enderror
                                                    </div>
                                                    <div class="row">
                                                        <div class="col-md-6">
                                                            <div class="form-group">
                                                                <label>Password <span class="text-danger">*</span></label>
                                                                <input type="password" name="password" id="password-tambah" value="{{ old('password') }}" placeholder="Masukkan Password" class="form-control @error('password') is-invalid @enderror" required>
                                                                @error('password')
                                                                <div class="invalid-feedback" style="display: block">
                                                                    {{ $message }}
                                                                </div>
                                                                @enderror
                                                            </div>
                                                        </div>
                                                        <div class="col-md-6">
                                                            <div class="form-group">
                                                                <label>Konfirmasi Password <span class="text-danger">*</span></label>
                                                                <input type="password" name="password_confirmation" id="password-confirmation-tambah" value="{{ old('password_confirmation') }}" placeholder="Masukkan Konfirmasi Password" class="form-control" required>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="form-group">
                                                        <label class="font-weight-bold">Role</label>
                                                        @foreach ($roles as $role)
                                                        <div class="form-check form-check-inline">
                                                            <input class="form-check-input" type="checkbox" name="role[]" value="{{ $role->name }}" id="check-{{ $role->id }}">
                                                            <label class="form-check-label" for="check-{{ $role->id }}">
                                                                {{ $role->name }}
                                                            </label>
                                                        </div>
                                                        @endforeach
                                                    </div>
                                                    <div class="modal-footer">
                                                        <button type="submit" class="btn btn-primary btn-submit">
                                                            <i class="fa fa-paper-plane"></i> Simpan
                                                        </button>
                                                        <button class="btn btn-warning text-white btn-reset" type="reset">
                                                            <i class="fa fa-redo"></i> Reset
                                                        </button>
                                                        <button type="button" class="btn btn-default" data-dismiss="modal">
                                                            <i class="fas fa-undo"></i> Kembali
                                                        </button>
                                                    </div>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            @endcan
                        </div>
                    </div>
                    <div class="card-body">
                        <table id="example1" class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th scope="col" style="text-align: center;width: 6%">NO.</th>
                                    <th scope="col">Nama User</th>
                                    <th scope="col">Role</th>
                                    <th scope="col" style="width: 15%;text-align: center">Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $nomer = 1; ?>
                                @foreach ($users as $no => $user)
                                <tr>
                                    <th>{{ $nomer++}}</th>
                                    <td>{{ $user->name }}</td>
                                    <td>
                                        @if(!empty($user->getRoleNames()))
                                            @foreach($user->getRoleNames() as $role)
                                                <label class="badge badge-success">{{ $role }}</label>
                                            @endforeach
                                        @endif
                                    </td>
                                    <td class="text-left">
                                        @can('users.edit')
                                            <button type="button" class="btn btn-warning text-white btn-sm m-1" title="Edit" data-toggle="modal" data-target="#modal-edit-{{ $user->id }}">
                                                <i class="fas fa-pencil-alt"></i>
                                            </button>
                                            <div class="modal fade" id="modal-edit-{{ $user->id }}">
                                                <div class="modal-dialog modal-xl">
                                                    <div class="modal-content">
                                                        <div class="modal-header">
                                                            <h4 class="modal-title"> Edit Data </h4>
                                                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                                <span aria-hidden="true">&times;</span>
                                                            </button>
                                                        </div>
                                                        <form action="{{ route('user.update', $user->id) }}" method="POST" enctype="multipart/form-data" class="form-edit-user">
                                                            @csrf
                                                            @method('PUT')
                                                            <div class="modal-body">
                                                                <div class="form-group">
                                                                    <label>Nama User <span class="text-danger">*</span> </label>
                                                                    <input type="text" name="name" value="{{ old('name', $user->name) }}"
                                                                        placeholder="Masukkan Nama User"
                                                                        class="form-control @error('name') is-invalid @enderror" required>
                                                                    @error('name')
                                                                    <div class="invalid-feedback" style="display: block">
                                                                        {{ $message }}
                                                                    </div>
                                                                    @enderror
                                                                </div>
                                                                <div class="form-group">
                                                                    <label>Email <span class="text-danger">*</span>  </label>
                                                                    <input type="email" name="email" value="{{ old('email', $user->email) }}"
                                                                        placeholder="Masukkan Email" class="form-control @error('email') is-invalid @enderror" required>
                                                                    @error('email')
                                                                    <div class="invalid-feedback" style="display: block">
                                                                        {{ $message }}
                                                                    </div>
                                                                    @enderror
                                                                </div>
                                                                <div class="row">
                                                                    <div class="col-md-6">
                                                                        <div class="form-group">
                                                                            <label>Password</label>
                                                                            <input type="password" name="password" value="{{ old('password') }}"
                                                                                placeholder="Masukkan Password"
                                                                                class="form-control @error('password') is-invalid @enderror">
                                                                            @error('password')
                                                                            <div class="invalid-feedback" style="display: block">
                                                                                {{ $message }}
                                                                            </div>
                                                                            @enderror
                                                                        </div>
                                                                    </div>
                                                                    <div class="col-md-6">
                                                                        <div class="form-group">
                                                                            <label>Konfirmasi Password</label>
                                                                            <input type="password" name="password_confirmation"
                                                                                value="{{ old('password_confirmation') }}"
                                                                                placeholder="Masukkan Konfirmasi Password" class="form-control">
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                <div class="form-group">
                                                                    <label class="font-weight-bold">Role</label>
                                                                    @foreach ($roles as $role)
                                                                        <div class="form-check form-check-inline">
                                                                            <input class="form-check-input" type="checkbox" name="role[]" value="{{ $role->name }}"
                                                                                id="check-{{ $role->id }}" {{ $user->roles->contains($role->id) ? 'checked' : '' }}>
                                                                            <label class="form-check-label" for="check-{{ $role->id }}">
                                                                                {{ $role->name }}
                                                                            </label>
                                                                        </div>
                                                                    @endforeach
                                                                </div>
                                                            </div>
                                                            <div class="modal-footer">
                                                                <button type="submit" class="btn btn-primary btn-submit">
                                                                    <i class="fa fa-paper-plane"></i> Simpan
                                                                </button>
                                                                <button class="btn btn-warning text-white btn-reset" type="reset">
                                                                    <i class="fa fa-redo"></i> Reset
                                                                </button>
                                                                <button type="button" class="btn btn-default" data-dismiss="modal">
                                                                    <i class="fas fa-undo"></i> Kembali
                                                                </button>
                                                            </div>
                                                        </form>
                                                    </div>
                                                </div>
                                            </div>
                                        @endcan
                                        @can('users.delete')
                                            <form action="{{ route('user.delete', $user->id) }}" method="POST" style="display:inline;" class="delete-form-{{ $user->id }}">
                                                @csrf
                                                @method('DELETE')
                                                <button type="button" class="btn btn-danger btn-sm delete m-1" data-id="{{ $user->id}}" data-name="{{ $user->name}}" title="Hapus">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </form>
                                        @endcan
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
<!-- /.content -->

@endsection

@push('scripts')
<script>
    $(document).ready(function() {
        // Auto buka modal jika ada error dari server (Form Tambah)
        @if($errors->any() && old('_method') === null)
            $('#modal-tambah').modal('show');
        @endif

        // Validasi Form Tambah User
        $('#form-tambah-user').on('submit', function(e) {
            var nameInput = $('#name-tambah').val().trim();
            var emailInput = $('#email-tambah').val().trim();
            var passwordInput = $('#password-tambah').val().trim();
            var passwordConfirmInput = $('#password-confirmation-tambah').val().trim();
            var isValid = true;

            // Reset semua error terlebih dahulu
            $('.invalid-feedback:not(.d-block)').remove();

            // Validasi Nama
            if (nameInput === '') {
                e.preventDefault();
                e.stopPropagation();
                isValid = false;

                $('#name-tambah').addClass('is-invalid');
                if ($('#name-tambah').siblings('.invalid-feedback').length === 0) {
                    $('#name-tambah').after('<div class="invalid-feedback" style="display: block">Nama User wajib diisi!</div>');
                }
            }

            // Validasi Email
            if (emailInput === '') {
                e.preventDefault();
                e.stopPropagation();
                isValid = false;

                $('#email-tambah').addClass('is-invalid');
                if ($('#email-tambah').siblings('.invalid-feedback').length === 0) {
                    $('#email-tambah').after('<div class="invalid-feedback" style="display: block">Email wajib diisi!</div>');
                }
            }

            // Validasi Password
            if (passwordInput === '') {
                e.preventDefault();
                e.stopPropagation();
                isValid = false;

                $('#password-tambah').addClass('is-invalid');
                if ($('#password-tambah').siblings('.invalid-feedback').length === 0) {
                    $('#password-tambah').after('<div class="invalid-feedback" style="display: block">Password wajib diisi!</div>');
                }
            }

            // Validasi Konfirmasi Password
            if (passwordConfirmInput === '') {
                e.preventDefault();
                e.stopPropagation();
                isValid = false;

                $('#password-confirmation-tambah').addClass('is-invalid');
                if ($('#password-confirmation-tambah').siblings('.invalid-feedback').length === 0) {
                    $('#password-confirmation-tambah').after('<div class="invalid-feedback" style="display: block">Konfirmasi Password wajib diisi!</div>');
                }
            } else if (passwordInput !== '' && passwordInput !== passwordConfirmInput) {
                e.preventDefault();
                e.stopPropagation();
                isValid = false;

                $('#password-tambah').addClass('is-invalid');
                $('#password-confirmation-tambah').addClass('is-invalid');

                if ($('#password-tambah').siblings('.invalid-feedback').length === 0) {
                    $('#password-tambah').after('<div class="invalid-feedback" style="display: block">Password tidak cocok!</div>');
                }
                if ($('#password-confirmation-tambah').siblings('.invalid-feedback').length === 0) {
                    $('#password-confirmation-tambah').after('<div class="invalid-feedback" style="display: block">Konfirmasi Password tidak cocok!</div>');
                }
            }

            if (!isValid) {
                // Focus ke input pertama yang error
                if (nameInput === '') {
                    $('#name-tambah').focus();
                } else if (emailInput === '') {
                    $('#email-tambah').focus();
                } else if (passwordInput === '') {
                    $('#password-tambah').focus();
                } else if (passwordConfirmInput === '' || passwordInput !== passwordConfirmInput) {
                    $('#password-tambah').focus();
                }
                return false;
            }
        });

        // Hapus error saat user mulai mengetik
        $('#name-tambah, #email-tambah, #password-tambah, #password-confirmation-tambah').on('input', function() {
            if ($(this).val().trim() !== '') {
                $(this).removeClass('is-invalid');
                $(this).siblings('.invalid-feedback:not([class*="d-block"])').remove();
            }
        });

        // Auto buka modal edit jika ada error dari server (Form Edit)
        @if($errors->any() && old('_method') === 'PUT')
            @foreach ($users as $user)
                @if(old('_token') && request()->route('id') == $user->id)
                    $('#modal-edit-{{ $user->id }}').modal('show');
                @endif
            @endforeach
        @endif

        // Validasi Form Edit user
        $('.form-edit-user').on('submit', function(e) {
            var nameInput = $(this).find('input[name="name"]');
            var emailInput = $(this).find('input[name="email"]');
            var passwordInput = $(this).find('input[name="password"]');
            var passwordConfirmInput = $(this).find('input[name="password_confirmation"]');
            var isValid = true;

            // Reset error yang dibuat JavaScript (bukan dari server)
            $(this).find('.invalid-feedback:not([class*="d-block"])').remove();

            // Validasi Nama
            if (nameInput.val().trim() === '') {
                e.preventDefault();
                e.stopPropagation();
                isValid = false;

                nameInput.addClass('is-invalid');
                if (nameInput.siblings('.invalid-feedback').length === 0) {
                    nameInput.after('<div class="invalid-feedback" style="display: block">Nama User wajib diisi!</div>');
                }
            }

            // Validasi Email
            if (emailInput.val().trim() === '') {
                e.preventDefault();
                e.stopPropagation();
                isValid = false;

                emailInput.addClass('is-invalid');
                if (emailInput.siblings('.invalid-feedback').length === 0) {
                    emailInput.after('<div class="invalid-feedback" style="display: block">Email wajib diisi!</div>');
                }
            }

            // Validasi Password (hanya jika diisi)
            if (passwordInput.val().trim() !== '' && passwordConfirmInput.val().trim() === '') {
                e.preventDefault();
                e.stopPropagation();
                isValid = false;

                passwordConfirmInput.addClass('is-invalid');
                if (passwordConfirmInput.siblings('.invalid-feedback').length === 0) {
                    passwordConfirmInput.after('<div class="invalid-feedback" style="display: block">Konfirmasi Password wajib diisi!</div>');
                }
            } else if (passwordInput.val().trim() !== '' && passwordInput.val() !== passwordConfirmInput.val()) {
                e.preventDefault();
                e.stopPropagation();
                isValid = false;

                passwordInput.addClass('is-invalid');
                passwordConfirmInput.addClass('is-invalid');

                if (passwordInput.siblings('.invalid-feedback').length === 0) {
                    passwordInput.after('<div class="invalid-feedback" style="display: block">Password tidak cocok!</div>');
                }
                if (passwordConfirmInput.siblings('.invalid-feedback').length === 0) {
                    passwordConfirmInput.after('<div class="invalid-feedback" style="display: block">Konfirmasi Password tidak cocok!</div>');
                }
            }

            if (!isValid) {
                // Focus ke input pertama yang error
                if (nameInput.val().trim() === '') {
                    nameInput.focus();
                } else if (emailInput.val().trim() === '') {
                    emailInput.focus();
                } else if (passwordInput.val().trim() !== '' && (passwordConfirmInput.val().trim() === '' || passwordInput.val() !== passwordConfirmInput.val())) {
                    passwordInput.focus();
                }
                return false;
            }
        });

        // Hapus error saat user mulai mengetik di form edit
        $('.form-edit-user input[name="name"], .form-edit-user input[name="email"], .form-edit-user input[name="password"], .form-edit-user input[name="password_confirmation"]').on('input', function() {
            if ($(this).val().trim() !== '') {
                $(this).removeClass('is-invalid');
                $(this).siblings('.invalid-feedback:not([class*="d-block"])').remove();
            }
        });
    });
</script>
@endpush
