@extends('layouts.app')

@section('title', __('employees'))

@push('styles')
<link href="{{ asset('css/employees.css') }}" rel="stylesheet">
@endpush

@section('content')
<div class="container-fluid">
    @php
        $isAddEmployeeModalOpen = (bool) session('open_employee_add_modal', false);
        $isEditEmployeeModalOpen = session()->has('edit_employee_id');
    @endphp
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb mb-1">
                    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">{{ __('dashboard') }}</a></li>
                    <li class="breadcrumb-item active" aria-current="page">{{ __('employees') }}</li>
                </ol>
            </nav>
            <h4 class="fw-bold mb-0">{{ __('employees.title') }}</h4>
            <div class="text-muted small">{{ __('employees.subtitle') }}</div>
        </div>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addEmployeeModal">
            <i class="bi bi-plus-lg me-2"></i> {{ __('employees.add_employee') }}
        </button>
    </div>

    @if(session('success'))
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            {{ session('success') }}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    @endif

    @if($errors->any())
        <div class="alert alert-danger">
            <ul class="mb-0">
                @foreach($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <div class="card employees-card border-0">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table align-middle mb-0">
                    <thead>
                        <tr>
                            <th>{{ __('employees.fields.full_name') }}</th>
                            <th>{{ __('employees.fields.phone') }}</th>
                            <th>{{ __('employees.fields.job_title') }}</th>
                            <th>{{ __('employees.fields.role') }}</th>
                            <th>{{ __('employees.fields.base_salary') }}</th>
                            <th>{{ __('employees.fields.general_percentage') }}</th>
                            <th>{{ __('employees.fields.role_percentage') }}</th>
                            <th class="text-end">{{ __('common.actions') }}</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($employees as $employee)
                            <tr>
                                <td class="fw-semibold">
                                    <div class="d-flex align-items-center gap-2">
                                        @if($employee->avatar_url)
                                            <img src="{{ $employee->avatar_url }}" alt="Avatar" class="rounded-circle" style="width: 32px; height: 32px; object-fit: cover;">
                                        @else
                                            <div class="rounded-circle bg-primary-subtle text-primary d-flex align-items-center justify-content-center" style="width: 32px; height: 32px;">
                                                <span class="fw-bold">{{ mb_substr($employee->full_name, 0, 1) }}</span>
                                            </div>
                                        @endif
                                        <span>{{ $employee->full_name }}</span>
                                    </div>
                                </td>
                                <td dir="ltr">{{ $employee->phone ?: '-' }}</td>
                                <td>{{ $employee->job_title ?: '-' }}</td>
                                <td>{{ $employee->role?->name ?: '-' }}</td>
                                <td>{{ number_format((int) $employee->base_salary, 0) }}</td>
                                <td>{{ (int) $employee->general_percentage }}%</td>
                                <td>{{ (int) $employee->role_percentage }}%</td>
                                <td class="text-end">
                                    <div class="btn-group">
                                        <form method="POST" action="{{ route('employees.toggle-active', $employee) }}" class="d-inline">
                                            @csrf
                                            <button
                                                type="submit"
                                                class="btn {{ ($employee->is_active ?? true) ? 'btn-outline-success' : 'btn-outline-secondary' }} js-confirm px-3"
                                                data-confirm-message="{{ ($employee->is_active ?? true) ? 'هل تريد إيقاف الموظف؟' : 'هل تريد تشغيل الموظف؟' }}"
                                            >
                                                <i class="bi {{ ($employee->is_active ?? true) ? 'bi-toggle-on' : 'bi-toggle-off' }} fs-5"></i>
                                            </button>
                                        </form>
                                        <button
                                            type="button"
                                            class="btn btn-outline-primary px-3"
                                            data-bs-toggle="modal"
                                            data-bs-target="#editEmployeeModal"
                                            data-id="{{ $employee->id }}"
                                            data-user_id="{{ $employee->user_id }}"
                                            data-username="{{ $employee->user?->username }}"
                                            data-full_name="{{ $employee->full_name }}"
                                            data-address="{{ $employee->address }}"
                                            data-phone="{{ $employee->phone }}"
                                            data-avatar_url="{{ $employee->avatar_url }}"
                                            data-job_title="{{ $employee->job_title }}"
                                            data-attendance_time="{{ $employee->attendance_time }}"
                                            data-departure_time="{{ $employee->departure_time }}"
                                            data-allow_outside_company="{{ $employee->allow_outside_company ? 1 : 0 }}"
                                            data-notes="{{ e($employee->notes) }}"
                                            data-base_salary="{{ $employee->base_salary }}"
                                            data-role_id="{{ $employee->role_id }}"
                                            data-general_percentage="{{ $employee->general_percentage }}"
                                            data-role_percentage="{{ $employee->role_percentage }}"
                                            data-commissions='@json($employee->serviceCommissions->mapWithKeys(fn ($c) => [$c->service_key => ["sales_percentage" => (int) $c->sales_percentage, "work_percentage" => $c->work_percentage === null ? null : (int) $c->work_percentage]]), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE)'
                                        >
                                            <i class="bi bi-pencil fs-5"></i>
                                        </button>
                                        <form method="POST" action="{{ route('employees.destroy', $employee) }}" class="d-inline">
                                            @csrf
                                            @method('DELETE')
                                            <button type="submit" class="btn btn-outline-danger js-confirm px-3" data-confirm-message="{{ __('employees.confirm_delete') }}">
                                                <i class="bi bi-trash fs-5"></i>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="8" class="text-center py-5 text-muted">
                                    <i class="bi bi-inbox fs-1 mb-3 d-block"></i>
                                    {{ __('employees.empty') }}
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
        <div class="card-footer">
            {{ $employees->links() }}
        </div>
    </div>
</div>

<div class="modal fade" id="addEmployeeModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">{{ __('employees.add_employee') }}</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="{{ route('employees.store') }}" method="POST" id="addEmployeeForm" enctype="multipart/form-data">
                @csrf
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">{{ __('employees.fields.full_name') }}</label>
                            <input type="text" name="full_name" class="form-control {{ $isAddEmployeeModalOpen && $errors->has('full_name') ? 'is-invalid' : '' }}" value="{{ old('full_name') }}" required>
                            @if($isAddEmployeeModalOpen)
                                @error('full_name')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('employees.fields.avatar') }}</label>
                            <input type="file" name="avatar" class="form-control {{ $isAddEmployeeModalOpen && $errors->has('avatar') ? 'is-invalid' : '' }}" accept="image/*">
                            @if($isAddEmployeeModalOpen)
                                @error('avatar')
                                    <div class="invalid-feedback d-block">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('employees.fields.phone') }}</label>
                            <input type="text" name="phone" class="form-control {{ $isAddEmployeeModalOpen && $errors->has('phone') ? 'is-invalid' : '' }}" value="{{ old('phone') }}" dir="ltr">
                            @if($isAddEmployeeModalOpen)
                                @error('phone')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('employees.fields.address') }}</label>
                            <input type="text" name="address" class="form-control {{ $isAddEmployeeModalOpen && $errors->has('address') ? 'is-invalid' : '' }}" value="{{ old('address') }}">
                            @if($isAddEmployeeModalOpen)
                                @error('address')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('employees.fields.job_title') }}</label>
                            <input type="text" name="job_title" class="form-control {{ $isAddEmployeeModalOpen && $errors->has('job_title') ? 'is-invalid' : '' }}" value="{{ old('job_title') }}">
                            @if($isAddEmployeeModalOpen)
                                @error('job_title')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('employees.fields.attendance_time') }}</label>
                            <input type="time" name="attendance_time" class="form-control {{ $isAddEmployeeModalOpen && $errors->has('attendance_time') ? 'is-invalid' : '' }}" value="{{ old('attendance_time') }}" required>
                            @if($isAddEmployeeModalOpen)
                                @error('attendance_time')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('employees.fields.departure_time') }}</label>
                            <input type="time" name="departure_time" class="form-control {{ $isAddEmployeeModalOpen && $errors->has('departure_time') ? 'is-invalid' : '' }}" value="{{ old('departure_time') }}" required>
                            @if($isAddEmployeeModalOpen)
                                @error('departure_time')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-12">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" role="switch" id="add_allow_outside_company" name="allow_outside_company" value="1" {{ old('allow_outside_company') ? 'checked' : '' }}>
                                <label class="form-check-label" for="add_allow_outside_company">{{ __('employees.fields.allow_outside_company') }}</label>
                            </div>
                        </div>
                        <div class="col-12">
                            <label class="form-label">{{ __('employees.fields.notes') }}</label>
                            <textarea name="notes" class="form-control {{ $isAddEmployeeModalOpen && $errors->has('notes') ? 'is-invalid' : '' }}" rows="3">{{ old('notes') }}</textarea>
                            @if($isAddEmployeeModalOpen)
                                @error('notes')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('employees.fields.base_salary') }}</label>
                            <input type="number" name="base_salary" class="form-control {{ $isAddEmployeeModalOpen && $errors->has('base_salary') ? 'is-invalid' : '' }}" value="{{ old('base_salary', 0) }}" min="0" step="1" required>
                            @if($isAddEmployeeModalOpen)
                                @error('base_salary')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('employees.fields.role') }}</label>
                            <select name="role_id" class="form-select {{ $isAddEmployeeModalOpen && $errors->has('role_id') ? 'is-invalid' : '' }}" id="add_role_id" required>
                                <option value="">{{ __('common.select') }}</option>
                                @foreach($roles as $role)
                                    <option value="{{ $role->id }}" {{ (string) old('role_id') === (string) $role->id ? 'selected' : '' }}>
                                        {{ $role->name }}
                                    </option>
                                @endforeach
                            </select>
                            @if($isAddEmployeeModalOpen)
                                @error('role_id')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('employees.fields.general_percentage') }}</label>
                            <input type="number" name="general_percentage" class="form-control {{ $isAddEmployeeModalOpen && $errors->has('general_percentage') ? 'is-invalid' : '' }}" value="{{ old('general_percentage', 0) }}" min="0" max="100" step="1" required>
                            @if($isAddEmployeeModalOpen)
                                @error('general_percentage')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-6" id="add_role_percentage_wrap">
                            <label class="form-label" id="add_role_percentage_label">{{ __('employees.fields.role_percentage') }}</label>
                            <input type="number" name="role_percentage" class="form-control {{ $isAddEmployeeModalOpen && $errors->has('role_percentage') ? 'is-invalid' : '' }}" value="{{ old('role_percentage', 0) }}" min="0" max="100" step="1" required>
                            @if($isAddEmployeeModalOpen)
                                @error('role_percentage')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">{{ __('employees.fields.username') }}</label>
                            <input type="text" name="username" class="form-control {{ $isAddEmployeeModalOpen && $errors->has('username') ? 'is-invalid' : '' }}" value="{{ old('username') }}" required autocomplete="off" dir="ltr">
                            @if($isAddEmployeeModalOpen)
                                @error('username')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">{{ __('employees.fields.password') }}</label>
                            <input type="password" name="password" class="form-control {{ $isAddEmployeeModalOpen && $errors->has('password') ? 'is-invalid' : '' }}" required autocomplete="new-password" dir="ltr">
                            @if($isAddEmployeeModalOpen)
                                @error('password')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">{{ __('employees.fields.password_confirmation') }}</label>
                            <input type="password" name="password_confirmation" class="form-control {{ $isAddEmployeeModalOpen && $errors->has('password_confirmation') ? 'is-invalid' : '' }}" required autocomplete="new-password" dir="ltr">
                            @if($isAddEmployeeModalOpen)
                                @error('password_confirmation')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-12">
                            <div class="border rounded p-3">
                                <div class="fw-semibold mb-3">{{ __('employees.fields.service_commissions') }}</div>
                                <div class="table-responsive">
                                    <table class="table table-sm align-middle mb-0">
                                        <thead>
                                            <tr>
                                                <th>{{ __('employees.fields.service') }}</th>
                                                <th class="text-nowrap">{{ __('employees.fields.sales_percentage') }}</th>
                                                <th class="text-nowrap">{{ __('employees.fields.work_percentage') }}</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach($serviceCommissionDefs as $def)
                                                <tr>
                                                    <td class="fw-semibold">{{ __($def['label_key']) }}</td>
                                                    <td style="min-width: 160px;">
                                                        <div class="input-group input-group-sm">
                                                            <input
                                                                type="number"
                                                                class="form-control {{ $isAddEmployeeModalOpen && $errors->has('commissions.'.$def['form_key'].'.sales_percentage') ? 'is-invalid' : '' }}"
                                                                id="add_commissions_{{ $def['form_key'] }}_sales"
                                                                name="commissions[{{ $def['form_key'] }}][sales_percentage]"
                                                                value="{{ old('commissions.'.$def['form_key'].'.sales_percentage', 0) }}"
                                                                min="0"
                                                                max="100"
                                                                step="1"
                                                                required
                                                            >
                                                            <span class="input-group-text">%</span>
                                                        </div>
                                                        @if($isAddEmployeeModalOpen)
                                                            @error('commissions.'.$def['form_key'].'.sales_percentage')
                                                                <div class="invalid-feedback d-block">{{ $message }}</div>
                                                            @enderror
                                                        @endif
                                                    </td>
                                                    <td style="min-width: 160px;">
                                                        @if($def['supports_work'])
                                                            <div class="input-group input-group-sm">
                                                                <input
                                                                    type="number"
                                                                    class="form-control {{ $isAddEmployeeModalOpen && $errors->has('commissions.'.$def['form_key'].'.work_percentage') ? 'is-invalid' : '' }}"
                                                                    id="add_commissions_{{ $def['form_key'] }}_work"
                                                                    name="commissions[{{ $def['form_key'] }}][work_percentage]"
                                                                    value="{{ old('commissions.'.$def['form_key'].'.work_percentage', 0) }}"
                                                                    min="0"
                                                                    max="100"
                                                                    step="1"
                                                                    required
                                                                >
                                                                <span class="input-group-text">%</span>
                                                            </div>
                                                            @if($isAddEmployeeModalOpen)
                                                                @error('commissions.'.$def['form_key'].'.work_percentage')
                                                                    <div class="invalid-feedback d-block">{{ $message }}</div>
                                                                @enderror
                                                            @endif
                                                        @else
                                                            <div class="text-muted">-</div>
                                                        @endif
                                                    </td>
                                                </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">{{ __('common.cancel') }}</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-save me-2"></i> {{ __('common.save') }}
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="editEmployeeModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">{{ __('employees.edit_employee') }}</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" id="editEmployeeForm" enctype="multipart/form-data">
                @csrf
                @method('PUT')
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">{{ __('employees.fields.full_name') }}</label>
                            <input type="text" name="full_name" id="edit_full_name" class="form-control {{ $isEditEmployeeModalOpen && $errors->has('full_name') ? 'is-invalid' : '' }}" required>
                            @if($isEditEmployeeModalOpen)
                                @error('full_name')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('employees.fields.phone') }}</label>
                            <input type="text" name="phone" id="edit_phone" class="form-control {{ $isEditEmployeeModalOpen && $errors->has('phone') ? 'is-invalid' : '' }}" dir="ltr">
                            @if($isEditEmployeeModalOpen)
                                @error('phone')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('employees.fields.avatar') }}</label>
                            <div class="d-flex align-items-center gap-2">
                                <img id="edit_avatar_preview" src="" alt="Avatar" class="rounded-circle d-none" style="width: 34px; height: 34px; object-fit: cover;">
                                <input type="file" name="avatar" id="edit_avatar" class="form-control {{ $isEditEmployeeModalOpen && $errors->has('avatar') ? 'is-invalid' : '' }}" accept="image/*">
                            </div>
                            @if($isEditEmployeeModalOpen)
                                @error('avatar')
                                    <div class="invalid-feedback d-block">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('employees.fields.username') }}</label>
                            <input type="text" name="username" id="edit_username" class="form-control {{ $isEditEmployeeModalOpen && $errors->has('username') ? 'is-invalid' : '' }}" required autocomplete="off" dir="ltr">
                            @if($isEditEmployeeModalOpen)
                                @error('username')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('employees.fields.address') }}</label>
                            <input type="text" name="address" id="edit_address" class="form-control {{ $isEditEmployeeModalOpen && $errors->has('address') ? 'is-invalid' : '' }}">
                            @if($isEditEmployeeModalOpen)
                                @error('address')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('employees.fields.job_title') }}</label>
                            <input type="text" name="job_title" id="edit_job_title" class="form-control {{ $isEditEmployeeModalOpen && $errors->has('job_title') ? 'is-invalid' : '' }}">
                            @if($isEditEmployeeModalOpen)
                                @error('job_title')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('employees.fields.attendance_time') }}</label>
                            <input type="time" name="attendance_time" id="edit_attendance_time" class="form-control {{ $isEditEmployeeModalOpen && $errors->has('attendance_time') ? 'is-invalid' : '' }}" required>
                            @if($isEditEmployeeModalOpen)
                                @error('attendance_time')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('employees.fields.departure_time') }}</label>
                            <input type="time" name="departure_time" id="edit_departure_time" class="form-control {{ $isEditEmployeeModalOpen && $errors->has('departure_time') ? 'is-invalid' : '' }}" required>
                            @if($isEditEmployeeModalOpen)
                                @error('departure_time')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-12">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" role="switch" id="edit_allow_outside_company" name="allow_outside_company" value="1">
                                <label class="form-check-label" for="edit_allow_outside_company">{{ __('employees.fields.allow_outside_company') }}</label>
                            </div>
                        </div>
                        <div class="col-12">
                            <label class="form-label">{{ __('employees.fields.notes') }}</label>
                            <textarea name="notes" id="edit_notes" class="form-control {{ $isEditEmployeeModalOpen && $errors->has('notes') ? 'is-invalid' : '' }}" rows="3"></textarea>
                            @if($isEditEmployeeModalOpen)
                                @error('notes')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('employees.fields.base_salary') }}</label>
                            <input type="number" name="base_salary" id="edit_base_salary" class="form-control {{ $isEditEmployeeModalOpen && $errors->has('base_salary') ? 'is-invalid' : '' }}" min="0" step="1" required>
                            @if($isEditEmployeeModalOpen)
                                @error('base_salary')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('employees.fields.role') }}</label>
                            <select name="role_id" class="form-select {{ $isEditEmployeeModalOpen && $errors->has('role_id') ? 'is-invalid' : '' }}" id="edit_role_id" required>
                                <option value="">{{ __('common.select') }}</option>
                                @foreach($roles as $role)
                                    <option value="{{ $role->id }}">{{ $role->name }}</option>
                                @endforeach
                            </select>
                            @if($isEditEmployeeModalOpen)
                                @error('role_id')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('employees.fields.general_percentage') }}</label>
                            <input type="number" name="general_percentage" id="edit_general_percentage" class="form-control {{ $isEditEmployeeModalOpen && $errors->has('general_percentage') ? 'is-invalid' : '' }}" min="0" max="100" step="1" required>
                            @if($isEditEmployeeModalOpen)
                                @error('general_percentage')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-6" id="edit_role_percentage_wrap">
                            <label class="form-label" id="edit_role_percentage_label">{{ __('employees.fields.role_percentage') }}</label>
                            <input type="number" name="role_percentage" id="edit_role_percentage" class="form-control {{ $isEditEmployeeModalOpen && $errors->has('role_percentage') ? 'is-invalid' : '' }}" min="0" max="100" step="1" required>
                            @if($isEditEmployeeModalOpen)
                                @error('role_percentage')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('employees.fields.password') }}</label>
                            <input type="password" name="password" id="edit_password" class="form-control {{ $isEditEmployeeModalOpen && $errors->has('password') ? 'is-invalid' : '' }}" autocomplete="new-password" dir="ltr">
                            @if($isEditEmployeeModalOpen)
                                @error('password')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('employees.fields.password_confirmation') }}</label>
                            <input type="password" name="password_confirmation" id="edit_password_confirmation" class="form-control {{ $isEditEmployeeModalOpen && $errors->has('password_confirmation') ? 'is-invalid' : '' }}" autocomplete="new-password" dir="ltr">
                            @if($isEditEmployeeModalOpen)
                                @error('password_confirmation')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            @endif
                        </div>
                        <div class="col-12">
                            <div class="border rounded p-3">
                                <div class="fw-semibold mb-3">{{ __('employees.fields.service_commissions') }}</div>
                                <div class="table-responsive">
                                    <table class="table table-sm align-middle mb-0">
                                        <thead>
                                            <tr>
                                                <th>{{ __('employees.fields.service') }}</th>
                                                <th class="text-nowrap">{{ __('employees.fields.sales_percentage') }}</th>
                                                <th class="text-nowrap">{{ __('employees.fields.work_percentage') }}</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach($serviceCommissionDefs as $def)
                                                <tr>
                                                    <td class="fw-semibold">{{ __($def['label_key']) }}</td>
                                                    <td style="min-width: 160px;">
                                                        <div class="input-group input-group-sm">
                                                            <input
                                                                type="number"
                                                                class="form-control {{ $isEditEmployeeModalOpen && $errors->has('commissions.'.$def['form_key'].'.sales_percentage') ? 'is-invalid' : '' }}"
                                                                id="edit_commissions_{{ $def['form_key'] }}_sales"
                                                                name="commissions[{{ $def['form_key'] }}][sales_percentage]"
                                                                value="0"
                                                                min="0"
                                                                max="100"
                                                                step="1"
                                                                required
                                                            >
                                                            <span class="input-group-text">%</span>
                                                        </div>
                                                        @if($isEditEmployeeModalOpen)
                                                            @error('commissions.'.$def['form_key'].'.sales_percentage')
                                                                <div class="invalid-feedback d-block">{{ $message }}</div>
                                                            @enderror
                                                        @endif
                                                    </td>
                                                    <td style="min-width: 160px;">
                                                        @if($def['supports_work'])
                                                            <div class="input-group input-group-sm">
                                                                <input
                                                                    type="number"
                                                                    class="form-control {{ $isEditEmployeeModalOpen && $errors->has('commissions.'.$def['form_key'].'.work_percentage') ? 'is-invalid' : '' }}"
                                                                    id="edit_commissions_{{ $def['form_key'] }}_work"
                                                                    name="commissions[{{ $def['form_key'] }}][work_percentage]"
                                                                    value="0"
                                                                    min="0"
                                                                    max="100"
                                                                    step="1"
                                                                    required
                                                                >
                                                                <span class="input-group-text">%</span>
                                                            </div>
                                                            @if($isEditEmployeeModalOpen)
                                                                @error('commissions.'.$def['form_key'].'.work_percentage')
                                                                    <div class="invalid-feedback d-block">{{ $message }}</div>
                                                                @enderror
                                                            @endif
                                                        @else
                                                            <div class="text-muted">-</div>
                                                        @endif
                                                    </td>
                                                </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">{{ __('common.cancel') }}</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-save me-2"></i> {{ __('common.save') }}
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script type="application/json" id="employeesConfig">
{!! json_encode([
    'roles' => $roles->map(fn ($role) => ['id' => $role->id, 'name' => $role->name])->values(),
    'baseEmployeesUrl' => route('employees'),
    'rolePercentageLabel' => __('employees.fields.role_percentage'),
    'rolePercentageForPrefix' => __('employees.role_percentage_for'),
    'confirmDeleteMessage' => __('employees.confirm_delete'),
    'serviceCommissionDefs' => $serviceCommissionDefs,
    'openAddModal' => (bool) session('open_employee_add_modal', false),
    'editEmployeeId' => session('edit_employee_id'),
    'oldInput' => [
        'username' => old('username'),
        'full_name' => old('full_name'),
        'address' => old('address'),
        'phone' => old('phone'),
        'job_title' => old('job_title'),
        'attendance_time' => old('attendance_time'),
        'departure_time' => old('departure_time'),
        'allow_outside_company' => old('allow_outside_company'),
        'notes' => old('notes'),
        'base_salary' => old('base_salary', 0),
        'role_id' => old('role_id'),
        'general_percentage' => old('general_percentage', 0),
        'role_percentage' => old('role_percentage', 0),
        'commissions' => old('commissions', []),
    ],
], JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE) !!}
</script>
<script>
    const configEl = document.getElementById('employeesConfig');
    let config = {};
    try {
        config = JSON.parse(configEl ? configEl.textContent : '{}');
    } catch (e) {
        config = {};
    }

    const roles = Array.isArray(config.roles) ? config.roles : [];
    const rolesById = {};
    roles.forEach((r) => {
        rolesById[String(r.id)] = r.name;
    });

    const baseEmployeesUrl = config.baseEmployeesUrl || '';
    const rolePercentageLabel = config.rolePercentageLabel || '';
    const rolePercentageForPrefix = config.rolePercentageForPrefix || '';
    const confirmDeleteMessage = config.confirmDeleteMessage || '';
    const serviceCommissionDefs = Array.isArray(config.serviceCommissionDefs) ? config.serviceCommissionDefs : [];

    function fillCommissionsFromServiceKeyMap(prefix, commissionsByServiceKey) {
        serviceCommissionDefs.forEach((def) => {
            const formKey = def.form_key || '';
            const serviceKey = def.service_key || '';
            if (! formKey || ! serviceKey) {
                return;
            }

            const salesInput = document.getElementById(`${prefix}_commissions_${formKey}_sales`);
            if (salesInput) {
                salesInput.value = commissionsByServiceKey?.[serviceKey]?.sales_percentage ?? 0;
            }

            const workInput = document.getElementById(`${prefix}_commissions_${formKey}_work`);
            if (workInput) {
                workInput.value = commissionsByServiceKey?.[serviceKey]?.work_percentage ?? 0;
            }
        });
    }

    function fillCommissionsFromFormKeyMap(prefix, commissionsByFormKey) {
        serviceCommissionDefs.forEach((def) => {
            const formKey = def.form_key || '';
            if (! formKey) {
                return;
            }

            const salesInput = document.getElementById(`${prefix}_commissions_${formKey}_sales`);
            if (salesInput) {
                salesInput.value = commissionsByFormKey?.[formKey]?.sales_percentage ?? 0;
            }

            const workInput = document.getElementById(`${prefix}_commissions_${formKey}_work`);
            if (workInput) {
                workInput.value = commissionsByFormKey?.[formKey]?.work_percentage ?? 0;
            }
        });
    }

    function syncRolePercentage(roleSelect, wrapEl, labelEl) {
        if (!roleSelect || !wrapEl || !labelEl) {
            return;
        }

        const roleId = roleSelect.value || '';
        if (!roleId) {
            wrapEl.classList.add('d-none');
            labelEl.textContent = rolePercentageLabel;
            return;
        }

        wrapEl.classList.remove('d-none');
        const roleName = rolesById[String(roleId)] || '';
        labelEl.textContent = roleName
            ? `${rolePercentageForPrefix}: ${roleName}`
            : rolePercentageLabel;
    }

    document.querySelectorAll('.js-confirm').forEach((btn) => {
        btn.addEventListener('click', (e) => {
            const message = btn.getAttribute('data-confirm-message') || confirmDeleteMessage;
            if (!confirm(message)) {
                e.preventDefault();
            }
        });
    });

    const addRoleSelect = document.getElementById('add_role_id');
    const addRolePercentageWrap = document.getElementById('add_role_percentage_wrap');
    const addRolePercentageLabel = document.getElementById('add_role_percentage_label');
    if (addRoleSelect) {
        addRoleSelect.addEventListener('change', () => syncRolePercentage(addRoleSelect, addRolePercentageWrap, addRolePercentageLabel));
        syncRolePercentage(addRoleSelect, addRolePercentageWrap, addRolePercentageLabel);
    }

    const editRoleSelect = document.getElementById('edit_role_id');
    const editRolePercentageWrap = document.getElementById('edit_role_percentage_wrap');
    const editRolePercentageLabel = document.getElementById('edit_role_percentage_label');
    if (editRoleSelect) {
        editRoleSelect.addEventListener('change', () => syncRolePercentage(editRoleSelect, editRolePercentageWrap, editRolePercentageLabel));
        syncRolePercentage(editRoleSelect, editRolePercentageWrap, editRolePercentageLabel);
    }

    const editModal = document.getElementById('editEmployeeModal');
    const editForm = document.getElementById('editEmployeeForm');
    const editFullName = document.getElementById('edit_full_name');
    const editAddress = document.getElementById('edit_address');
    const editPhone = document.getElementById('edit_phone');
    const editJobTitle = document.getElementById('edit_job_title');
    const editAttendanceTime = document.getElementById('edit_attendance_time');
    const editDepartureTime = document.getElementById('edit_departure_time');
    const editAllowOutsideCompany = document.getElementById('edit_allow_outside_company');
    const editNotes = document.getElementById('edit_notes');
    const editBaseSalary = document.getElementById('edit_base_salary');
    const editGeneralPercentage = document.getElementById('edit_general_percentage');
    const editRolePercentage = document.getElementById('edit_role_percentage');
    const editUsername = document.getElementById('edit_username');
    const editPassword = document.getElementById('edit_password');
    const editPasswordConfirmation = document.getElementById('edit_password_confirmation');
    const editAvatarPreview = document.getElementById('edit_avatar_preview');
    const editAvatarInput = document.getElementById('edit_avatar');

    if (editModal) {
        editModal.addEventListener('show.bs.modal', (event) => {
            const button = event.relatedTarget;
            const id = button.getAttribute('data-id') || '';

            editForm.action = `${baseEmployeesUrl}/${id}`;
            editFullName.value = button.getAttribute('data-full_name') || '';
            editAddress.value = button.getAttribute('data-address') || '';
            editPhone.value = button.getAttribute('data-phone') || '';
            editJobTitle.value = button.getAttribute('data-job_title') || '';
            editAttendanceTime.value = (button.getAttribute('data-attendance_time') || '').slice(0, 5);
            editDepartureTime.value = (button.getAttribute('data-departure_time') || '').slice(0, 5);
            editAllowOutsideCompany.checked = (button.getAttribute('data-allow_outside_company') || '0') === '1';
            editNotes.value = button.getAttribute('data-notes') || '';
            editBaseSalary.value = button.getAttribute('data-base_salary') || 0;
            editUsername.value = button.getAttribute('data-username') || '';
            editPassword.value = '';
            editPasswordConfirmation.value = '';
            editRoleSelect.value = button.getAttribute('data-role_id') || '';
            editGeneralPercentage.value = button.getAttribute('data-general_percentage') || 0;
            editRolePercentage.value = button.getAttribute('data-role_percentage') || 0;
            syncRolePercentage(editRoleSelect, editRolePercentageWrap, editRolePercentageLabel);

            const avatarUrl = button.getAttribute('data-avatar_url') || '';
            if (editAvatarInput) {
                editAvatarInput.value = '';
            }
            if (editAvatarPreview) {
                if (avatarUrl) {
                    editAvatarPreview.src = avatarUrl;
                    editAvatarPreview.classList.remove('d-none');
                } else {
                    editAvatarPreview.src = '';
                    editAvatarPreview.classList.add('d-none');
                }
            }

            let commissions = {};
            try {
                commissions = JSON.parse(button.getAttribute('data-commissions') || '{}');
            } catch (e) {
                commissions = {};
            }
            fillCommissionsFromServiceKeyMap('edit', commissions);
        });
    }

    if (config.openAddModal) {
        const addModalEl = document.getElementById('addEmployeeModal');
        if (addModalEl) {
            const modal = bootstrap.Modal.getOrCreateInstance(addModalEl);
            modal.show();
        }
    }

    if (config.editEmployeeId) {
        const editModalEl = document.getElementById('editEmployeeModal');
        if (editModalEl) {
            editForm.action = `${baseEmployeesUrl}/${config.editEmployeeId}`;
            editFullName.value = config.oldInput?.full_name || '';
            editAddress.value = config.oldInput?.address || '';
            editPhone.value = config.oldInput?.phone || '';
            editJobTitle.value = config.oldInput?.job_title || '';
            editAttendanceTime.value = (config.oldInput?.attendance_time || '').slice(0, 5);
            editDepartureTime.value = (config.oldInput?.departure_time || '').slice(0, 5);
            editAllowOutsideCompany.checked = Boolean(config.oldInput?.allow_outside_company);
            editNotes.value = config.oldInput?.notes || '';
            editBaseSalary.value = config.oldInput?.base_salary || 0;
            editUsername.value = config.oldInput?.username || '';
            editPassword.value = '';
            editPasswordConfirmation.value = '';
            editRoleSelect.value = config.oldInput?.role_id || '';
            editGeneralPercentage.value = config.oldInput?.general_percentage || 0;
            editRolePercentage.value = config.oldInput?.role_percentage || 0;
            syncRolePercentage(editRoleSelect, editRolePercentageWrap, editRolePercentageLabel);
            fillCommissionsFromFormKeyMap('edit', config.oldInput?.commissions || {});
            const modal = bootstrap.Modal.getOrCreateInstance(editModalEl);
            modal.show();
        }
    }
</script>
@endpush
