@extends('layouts.app')

@php
    use App\Models\User;
    $request = request();
    $userid = $request->id ?? '';
    $userdetails = $userid ? User::find($userid) : null;
    $name = $userdetails->name ?? '';
    $email = $userdetails->email ?? '';
    $username = $userdetails->username ?? '';
    $accesslevel = $userdetails->userrole ?? '';
    $districtv = $userdetails->district ?? '';
    $partner = $userdetails->partner ?? '';
    $districtlist = array_map('trim', explode(',', (string) $districtv));
@endphp

@section('title', ($userid ? 'Update User' : 'Create User') . ' - NGBVD')

@section('content')
<div class="ngbvd-page-header mb-3">
    <div>
        <span class="ngbvd-kicker">Users & Access</span>
        <h2 class="ngbvd-page-title">{{ $userid ? 'Update User Account' : 'Create User Account' }}</h2>
        <p class="ngbvd-page-subtitle">Create users, assign access level, attach districts and configure partner access.</p>
    </div>
    <a href="{{ url('/users/viewusers') }}" class="btn ngbvd-btn-soft"><i class="ti-list"></i> View Users</a>
</div>

<div class="card ngbvd-user-card">
    <form method="POST" action="{{ url('users/processuser') }}">
        @csrf
        <input type="hidden" name="id" value="{{ $userid }}">
        <div class="ngbvd-user-form-grid">
            <div>
                <label for="name">Full Name <span class="text-danger">*</span></label>
                <input id="name" type="text" class="form-control @error('name') is-invalid @enderror" name="name" value="{{ old('name', $name) }}" required autocomplete="name" autofocus>
                @error('name')<span class="invalid-feedback d-block"><strong>{{ $message }}</strong></span>@enderror
            </div>
            <div>
                <label for="email">E-Mail Address <span class="text-danger">*</span></label>
                <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email', $email) }}" required autocomplete="email">
                @error('email')<span class="invalid-feedback d-block"><strong>{{ $message }}</strong></span>@enderror
            </div>
            <div>
                <label for="username">Username <span class="text-danger">*</span></label>
                <input id="username" type="text" class="form-control @error('username') is-invalid @enderror" name="username" value="{{ old('username', $username) }}" required autocomplete="username">
                @error('username')<span class="invalid-feedback d-block"><strong>{{ $message }}</strong></span>@enderror
            </div>
            <div>
                <label for="accesslevel">Access Level <span class="text-danger">*</span></label>
                <select class="form-control @error('accesslevel') is-invalid @enderror" name="accesslevel" id="accesslevel" required>
                    @foreach($roles as $role)
                        <option value="{{ $role->id }}" @if($accesslevel == $role->id) selected @endif>{{ $role->name }}</option>
                    @endforeach
                </select>
                @error('accesslevel')<span class="invalid-feedback d-block"><strong>{{ $message }}</strong></span>@enderror
            </div>
            <div class="full" id="district">
                <label for="district_select">District Access</label>
                <select id="district_select" class="form-control @error('district') is-invalid @enderror" name="district[]" multiple>
                    <option value="*" @if(in_array('*', $districtlist)) selected @endif>All Districts</option>
                    @foreach($districts as $district)
                        <option value="{{ $district->id }}" @if(in_array($district->id, $districtlist)) selected @endif>{{ $district->name }}</option>
                    @endforeach
                </select>
                @error('district')<span class="invalid-feedback d-block"><strong>{{ $message }}</strong></span>@enderror
            </div>
            <div class="full">
                <label class="d-flex align-items-center" style="gap:10px;">
                    <input id="partner" type="checkbox" @if(!empty($partner)) checked @endif class="checkbox checkbox-inline @error('partner') is-invalid @enderror" name="partner" value="1" autocomplete="new-partner">
                    <span>This account belongs to a partner organization</span>
                </label>
                @error('partner')<span class="invalid-feedback d-block"><strong>{{ $message }}</strong></span>@enderror
            </div>
            <div class="full" id="partners"></div>
            @if(empty($userid))
                <div>
                    <label for="password">Password <span class="text-danger">*</span></label>
                    <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="new-password">
                    @error('password')<span class="invalid-feedback d-block"><strong>{{ $message }}</strong></span>@enderror
                </div>
                <div>
                    <label for="password-confirm">Confirm Password <span class="text-danger">*</span></label>
                    <input id="password-confirm" type="password" class="form-control" name="password_confirmatio" required autocomplete="new-password">
                </div>
            @endif
        </div>
        <div class="d-flex justify-content-end mt-4" style="gap:10px;">
            <a href="{{ url('/users/viewusers') }}" class="btn ngbvd-btn-soft">Cancel</a>
            <button type="submit" class="btn ngbvd-btn-primary"><i class="ti-save"></i> {{ $userid ? 'Update User' : 'Create User' }}</button>
        </div>
    </form>
</div>
@endsection

@push('scripts')
<script>
    jQuery(function($){
        function refreshSelectize(scope) {
            if ($.fn.selectize) {
                $(scope).find('select').each(function(){ if (!this.selectize) { $(this).selectize({ allowEmptyOption: true }); } });
            }
        }

        $(document).on('change', '#accesslevel', function(){
            var accesslevelid = $(this).val();
            $.ajax({
                type: 'get',
                url: '/findDistrict',
                data: {'id': accesslevelid},
                success: function(data){
                    var multiple = (accesslevelid != 1 && accesslevelid != 2) ? 'multiple' : '';
                    var html = '<label for="district_select">District Access</label>';
                    html += '<select id="district_select" class="form-control" name="district[]" ' + multiple + '>';
                    if (accesslevelid == 1 || accesslevelid == 2) { html += '<option value="*" selected>All Districts</option>'; }
                    else { html += '<option value="" disabled>Select Districts</option>'; }
                    for (var i = 0; i < data.length; i++) { html += '<option value="' + data[i].id + '">' + data[i].name + '</option>'; }
                    html += '</select>';
                    $('#district').html(html);
                    refreshSelectize('#district');
                }
            });
        });

        $(document).on('change', '#partner', function(){
            if (!$(this).prop('checked')) { $('#partners').empty(); return; }
            $.ajax({
                type: 'get',
                url: '/findPartner',
                success: function(data){
                    var html = '<label for="partnerid">Partner Organization</label><select id="partnerid" class="form-control" name="partnerid"><option value="" selected disabled>Select Partner</option>';
                    for (var i = 0; i < data.length; i++) { html += '<option value="' + data[i].id + '">' + data[i].name + '</option>'; }
                    html += '</select>';
                    $('#partners').html(html);
                    refreshSelectize('#partners');
                }
            });
        });
    });
</script>
@endpush
