@extends('layouts.app')
@section('title', isset($role) ? 'Edit Role' : 'Create Role')

@section('breadcrumb')
    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
    <li class="breadcrumb-item"><a href="{{ route('admin.roles.index') }}">Roles</a></li>
    <li class="breadcrumb-item active">{{ isset($role) ? 'Edit: '.$role->name : 'Create Role' }}</li>
@endsection

@section('content')
<div class="page-header">
    <div>
        <h1 class="page-title">{{ isset($role) ? 'Edit Role' : 'Create Role' }}</h1>
        <p class="page-subtitle">Configure permissions for this role</p>
    </div>
    <a href="{{ route('admin.roles.index') }}" class="btn btn-outline-secondary">
        <i class="bi bi-arrow-left me-1"></i>Back
    </a>
</div>

<form method="POST"
      action="{{ isset($role) ? route('admin.roles.update', $role) : route('admin.roles.store') }}"
      id="roleForm">
@csrf
@if(isset($role)) @method('PUT') @endif

<div class="row g-4">
    <div class="col-12 col-xl-4">
        <div class="card">
            <div class="card-header"><i class="bi bi-shield me-2 text-primary"></i>Role Details</div>
            <div class="card-body">
                <div class="mb-3">
                    <label class="form-label">Role Name (slug) <span class="required">*</span></label>
                    <input type="text" name="name" class="form-control @error('name') is-invalid @enderror"
                           value="{{ old('name', $role->name ?? '') }}"
                           placeholder="e.g. accountant"
                           {{ isset($role) && $role->is_system ? 'readonly style=background:#f8f9fa' : '' }} required>
                    <div class="form-text">Lowercase, no spaces. Used internally.</div>
                    @error('name')<div class="invalid-feedback">{{ $message }}</div>@enderror
                </div>
                <div class="mb-3">
                    <label class="form-label">Display Name</label>
                    <input type="text" name="display_name" class="form-control"
                           value="{{ old('display_name', $role->display_name ?? '') }}"
                           placeholder="e.g. Accountant">
                </div>
                <div class="mb-3">
                    <label class="form-label">Description</label>
                    <textarea name="description" class="form-control" rows="3"
                              placeholder="Describe what this role can do">{{ old('description', $role->description ?? '') }}</textarea>
                </div>
                <div class="d-flex gap-2">
                    <a href="{{ route('admin.roles.index') }}" class="btn btn-outline-secondary flex-fill">Cancel</a>
                    <button type="submit" class="btn btn-primary flex-fill" id="saveBtn">
                        <i class="bi bi-check-circle me-1"></i>{{ isset($role) ? 'Save Changes' : 'Create Role' }}
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div class="col-12 col-xl-8">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span><i class="bi bi-key me-2 text-primary"></i>Permissions</span>
                <div class="d-flex gap-2">
                    <button type="button" class="btn btn-outline-secondary btn-sm" id="checkAll">
                        <i class="bi bi-check-all me-1"></i>Check All
                    </button>
                    <button type="button" class="btn btn-outline-secondary btn-sm" id="uncheckAll">
                        <i class="bi bi-x me-1"></i>Uncheck All
                    </button>
                </div>
            </div>
            <div class="card-body">
                @php
                    $moduleLabels = [
                        'accounts'      => 'Chart of Accounts',
                        'vouchers'      => 'Accounting Vouchers',
                        'ar'            => 'Accounts Receivable (AR)',
                        'ap'            => 'Accounts Payable (AP)',
                        'inventory'     => 'Inventory',
                        'manufacturing' => 'Manufacturing',
                        'reports'       => 'Reports',
                        'settings'      => 'Settings',
                        'users'         => 'Users & Roles',
                        'audit'         => 'Audit Trail',
                        'budget'        => 'Budget',
                        'banking'       => 'Banking',
                    ];
                @endphp

                @foreach($permissions as $module => $modulePerms)
                <div class="mb-4">
                    <div class="d-flex align-items-center justify-content-between mb-2">
                        <div class="form-section-title mb-0" style="border:none;padding:0">
                            {{ $moduleLabels[$module] ?? ucfirst($module) }}
                        </div>
                        <button type="button" class="btn btn-link btn-sm p-0 text-muted module-check" data-module="{{ $module }}">
                            Select all
                        </button>
                    </div>
                    <div class="row g-2">
                        @foreach($modulePerms as $perm)
                        <div class="col-12 col-sm-6 col-md-4">
                            <div class="form-check">
                                <input class="form-check-input perm-check perm-{{ $module }}"
                                       type="checkbox" name="permissions[]"
                                       value="{{ $perm->id }}" id="perm-{{ $perm->id }}"
                                       {{ in_array($perm->id, old('permissions', $rolePermissionIds ?? [])) ? 'checked' : '' }}>
                                <label class="form-check-label" for="perm-{{ $perm->id }}" style="font-size:13px">
                                    {{ $perm->display_name ?? ucfirst($perm->action) }}
                                </label>
                            </div>
                        </div>
                        @endforeach
                    </div>
                </div>
                @endforeach
            </div>
        </div>
    </div>
</div>
</form>
@endsection

@push('scripts')
<script>
document.getElementById('checkAll').addEventListener('click', () =>
    document.querySelectorAll('.perm-check').forEach(c => c.checked = true));
document.getElementById('uncheckAll').addEventListener('click', () =>
    document.querySelectorAll('.perm-check').forEach(c => c.checked = false));
document.querySelectorAll('.module-check').forEach(btn => {
    btn.addEventListener('click', function() {
        const m  = this.dataset.module;
        const all = document.querySelectorAll('.perm-' + m);
        const anyUnchecked = [...all].some(c => !c.checked);
        all.forEach(c => c.checked = anyUnchecked);
        this.textContent = anyUnchecked ? 'Deselect all' : 'Select all';
    });
});
document.getElementById('roleForm').addEventListener('submit', function() {
    const btn = document.getElementById('saveBtn');
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Saving...';
    btn.disabled = true;
});
</script>
@endpush
