@extends('layouts.app')

@section('content')
<div class="row">
    <div class="col-sm-12">
        <div class="page-title-box">
            <h4 class="page-title">Create Role</h4>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-12">
        <form id="role-form">
            @csrf
            <div class="card">
                <div class="card-body">
                    <div class="mb-3">
                        <label for="name" class="form-label">Role Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="name" name="name" maxlength="255" required placeholder="e.g. HR Manager">
                    </div>

                    <hr>
                    <h5 class="mb-4">Permissions <span class="text-danger">*</span></h5>

                    @foreach($permissionsByModule as $moduleName => $submodules)
                        <div class="module-group mb-4 p-3 border rounded">
                            <h6 class="text-primary border-bottom pb-2">{{ $moduleName }} MODULE</h6>
                            
                            @foreach($submodules as $submoduleName => $permissions)
                                <div class="submodule-group mt-3 mb-3 ms-3">
                                    <div class="d-flex align-items-center mb-2">
                                        <h7 class="fw-bold me-3">{{ $submoduleName }}</h7>
                                        <div class="form-check">
                                            <input class="form-check-input select-all-submodule" type="checkbox" id="all_{{ Str::slug($moduleName . $submoduleName) }}">
                                            <label class="form-check-label text-muted small" for="all_{{ Str::slug($moduleName . $submoduleName) }}">Select All</label>
                                        </div>
                                    </div>
                                    
                                    <div class="row ms-2">
                                        @foreach($permissions as $permission)
                                            <div class="col-md-3 mb-2">
                                                <div class="form-check">
                                                    <input class="form-check-input permission-checkbox" type="checkbox" name="permissions[]" value="{{ $permission->id }}" id="perm_{{ $permission->id }}">
                                                    <label class="form-check-label" for="perm_{{ $permission->id }}">
                                                        {{ ucwords(str_replace('-', ' ', $permission->name)) }}
                                                    </label>
                                                </div>
                                            </div>
                                        @endforeach
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    @endforeach

                    <div class="mt-4">
                        <button type="submit" class="btn btn-primary">Create Role</button>
                        <a href="{{ route('settings.roles.index') }}" class="btn btn-secondary">Cancel</a>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>
@endsection

@section('scripts')
<script>
$(document).ready(function() {
    // Select all permissions in a submodule
    $('.select-all-submodule').change(function() {
        $(this).closest('.submodule-group').find('.permission-checkbox').prop('checked', $(this).prop('checked'));
    });

    $('#role-form').submit(function(e) {
        e.preventDefault();

        let btn = $(this).find('button[type=submit]');
        btn.prop('disabled', true);

        $.ajax({
            url: "{{ route('settings.roles.store') }}",
            type: 'POST',
            data: $(this).serialize(),
            success: function(response) {
                if (response.status) {
                    Swal.fire('Success', response.message, 'success')
                        .then(() => window.location.href = "{{ route('settings.roles.index') }}");
                }
            },
            error: function(xhr) {
                btn.prop('disabled', false);

                if (xhr.status === 422) {
                    let errors = xhr.responseJSON.errors;
                    let errorList = '<ul style="text-align: left;">';

                    $.each(errors, function(field, messages) {
                        $.each(messages, function(index, message) {
                            errorList += '<li>' + message + '</li>';
                        });
                    });

                    errorList += '</ul>';

                    Swal.fire({
                        title: 'Validation Error',
                        html: errorList,
                        icon: 'error'
                    });
                } else {
                    Swal.fire('Error', 'An error occurred. Please try again.', 'error');
                }
            }
        });
    });
});
</script>
@endsection
