@extends('layouts.app')

@section('content')
<div class="container-fluid">
    
    <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-3">
        <div>
            <h2 class="fw-bold text-dark mb-0"><i class="bi bi-people-fill me-2"></i>Personal</h2>
            <p class="text-muted mb-0">Gestiona los accesos y roles de tu equipo</p>
        </div>
        <div class="d-flex gap-2">
            @if($currentUser->isSuperAdmin())
                <a href="{{ route('roles.permissions.index') }}" class="btn btn-outline-dark fw-bold shadow-sm">
                    <i class="bi bi-shield-lock-fill me-2"></i> Roles y Permisos
                </a>
            @endif
            @if(count($currentUser->getAllowedRolesForCreate ?? ['waiter']) > 0 || $currentUser->isSuperAdmin() || $currentUser->role === 'admin' || $currentUser->role === 'gerente')
                <button class="btn btn-primary fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#createUserModal">
                    <i class="bi bi-person-plus-fill me-2"></i> Nuevo Usuario
                </button>
            @endif
        </div>
    </div>

    <div class="card border-0 shadow-sm">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="table-light">
                        <tr>
                            <th class="ps-4">Usuario</th>
                            <th>Rol / Cargo</th>
                            <th>Email de Acceso</th>
                            <th>Fecha Registro</th>
                            <th class="text-end pe-4">Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($users as $user)
                            <tr @if($user->isSuperAdmin()) class="table-light" @endif>
                                <td class="ps-4">
                                    <div class="d-flex align-items-center">
                                        <div class="avatar-circle me-3 bg-{{ $user->getRoleColor() }} 
                                            @if($user->isSuperAdmin()) border border-dark border-2 @endif">
                                            {{ substr($user->name, 0, 1) }}
                                        </div>
                                        <div>
                                            <div class="fw-bold d-flex align-items-center gap-2">
                                                {{ $user->name }}
                                                @if($user->isSuperAdmin())
                                                    <span class="badge bg-dark text-white" style="font-size: 0.6rem;" title="Cuenta protegida">
                                                        <i class="bi bi-shield-lock-fill me-1"></i>SISTEMA
                                                    </span>
                                                @endif
                                            </div>
                                            @if($user->id === $currentUser->id)
                                                <span class="badge bg-light text-dark border" style="font-size: 0.6rem;">TÚ</span>
                                            @endif
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    @php
                                        $color = $user->getRoleColor();
                                        $bgOp = match($color) {
                                            'dark' => 'bg-dark bg-opacity-10 text-dark border-dark',
                                            'danger' => 'bg-danger bg-opacity-10 text-danger border-danger',
                                            'warning' => 'bg-warning bg-opacity-10 text-warning-emphasis border-warning',
                                            'primary' => 'bg-primary bg-opacity-10 text-primary border-primary',
                                            'success' => 'bg-success bg-opacity-10 text-success border-success',
                                            'info' => 'bg-info bg-opacity-10 text-info-emphasis border-info',
                                            default => 'bg-secondary bg-opacity-10 text-secondary border-secondary',
                                        };
                                    @endphp
                                    <span class="badge border px-3 py-2 {{ $bgOp }}">
                                        {{ $user->getRoleLabel() }}
                                    </span>
                                </td>
                                <td class="text-muted">{{ $user->email }}</td>
                                <td class="text-muted small">{{ $user->created_at->format('d/m/Y H:i') }}</td>
                                <td class="text-end pe-4">
                                    @php
                                        $canEdit = true;
                                        $canDelete = true;

                                        if ($user->isSuperAdmin()) {
                                            if (!$currentUser->isSuperAdmin()) {
                                                $canEdit = false;
                                                $canDelete = false;
                                            } else {
                                                $canDelete = false;
                                                $canEdit = ($currentUser->id === $user->id);
                                            }
                                        }

                                        if (!$currentUser->isSuperAdmin() && !$currentUser->isSuperAdmin()) {
                                            if (in_array($user->role, ['admin', 'gerente']) && $currentUser->role !== 'admin' && !$currentUser->isSuperAdmin()) {
                                                $canEdit = false;
                                                $canDelete = false;
                                            }
                                        }
                                    @endphp

                                    @if($canEdit)
                                        <button class="btn btn-sm btn-link text-dark p-0 me-3" onclick='editUser(@json($user))' title="Editar">
                                            <i class="bi bi-pencil-square fs-5"></i>
                                        </button>
                                    @else
                                        <button class="btn btn-sm btn-link text-secondary p-0 me-3" disabled title="{{ $user->isSuperAdmin() ? 'Cuenta de sistema protegida' : 'Sin permiso para editar' }}">
                                            <i class="bi bi-pencil-square fs-5"></i>
                                        </button>
                                    @endif
                                    
                                    @if($canDelete && $user->id !== $currentUser->id)
                                        <form action="{{ route('users.destroy', $user->id) }}" method="POST" class="d-inline" onsubmit="return confirm('¿Estás seguro de eliminar a {{ $user->name }}?');">
                                            @csrf @method('DELETE')
                                            <button class="btn btn-sm btn-link text-danger p-0 border-0 bg-transparent" title="Eliminar">
                                                <i class="bi bi-trash fs-5"></i>
                                            </button>
                                        </form>
                                    @else
                                        <button class="btn btn-sm btn-link text-secondary p-0 border-0 bg-transparent" disabled title="{{ $user->isSuperAdmin() ? 'Protegido: no se puede eliminar' : ($user->id === $currentUser->id ? 'No puedes eliminarte a ti mismo' : 'Sin permiso') }}">
                                            <i class="bi bi-trash fs-5"></i>
                                        </button>
                                    @endif
                                </td>
                            </tr>
                        @endforeach
                        @if($users->count() === 0)
                            <tr>
                                <td colspan="5" class="text-center py-5 text-muted">
                                    <i class="bi bi-people fs-1 d-block mb-3 opacity-25"></i>
                                    No hay usuarios registrados.
                                </td>
                            </tr>
                        @endif
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

@php
    $allowedRoles = ['cashier', 'waiter', 'kitchen'];
    if ($currentUser->isSuperAdmin()) {
        $allowedRoles = ['superadmin', 'admin', 'gerente', 'cashier', 'waiter', 'kitchen'];
    } elseif ($currentUser->role === 'admin') {
        $allowedRoles = ['admin', 'gerente', 'cashier', 'waiter', 'kitchen'];
    } elseif ($currentUser->role === 'gerente') {
        $allowedRoles = ['cashier', 'waiter', 'kitchen'];
    }
@endphp

<div class="modal fade" id="createUserModal" tabindex="-1">
    <div class="modal-dialog">
        <form action="{{ route('users.store') }}" method="POST" class="modal-content">
            @csrf
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title fw-bold"><i class="bi bi-person-plus-fill me-2"></i>Registrar Personal</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label fw-bold">Nombre Completo</label>
                    <input type="text" name="name" class="form-control" required placeholder="Ej: Juan Pérez">
                </div>
                <div class="mb-3">
                    <label class="form-label fw-bold">Correo Electrónico (Login)</label>
                    <input type="email" name="email" class="form-control" required placeholder="juan@restaurante.com">
                </div>
                <div class="row mb-3">
                    <div class="col-6">
                        <label class="form-label fw-bold">Contraseña</label>
                        <input type="password" name="password" class="form-control" required minlength="6">
                    </div>
                    <div class="col-6">
                        <label class="form-label fw-bold">Rol / Permisos</label>
                        <select name="role" class="form-select" required>
                            @foreach($allowedRoles as $r)
                                @php
                                    $rLabels = \App\Models\Permission::getRoles();
                                @endphp
                                <option value="{{ $r }}">{{ $rLabels[$r]['label'] ?? $r }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>
                <div class="small text-muted">
                    <i class="bi bi-info-circle me-1"></i>
                    Los permisos específicos por módulo se configuran en la sección "Roles y Permisos".
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                <button type="submit" class="btn btn-primary fw-bold">Guardar Usuario</button>
            </div>
        </form>
    </div>
</div>

<div class="modal fade" id="editUserModal" tabindex="-1">
    <div class="modal-dialog">
        <form id="editUserForm" method="POST" class="modal-content">
            @csrf @method('PUT')
            <div class="modal-header bg-warning">
                <h5 class="modal-title fw-bold text-dark"><i class="bi bi-pencil-square me-2"></i>Editar Usuario</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label fw-bold">Nombre</label>
                    <input type="text" name="name" id="edit_name" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label class="form-label fw-bold">Email</label>
                    <input type="email" name="email" id="edit_email" class="form-control" required>
                </div>
                <div class="row mb-3">
                    <div class="col-6">
                        <label class="form-label fw-bold">Nueva Contraseña</label>
                        <input type="password" name="password" class="form-control" placeholder="Dejar vacío para no cambiar">
                    </div>
                    <div class="col-6">
                        <label class="form-label fw-bold">Rol</label>
                        <select name="role" id="edit_role" class="form-select">
                            @foreach($allowedRoles as $r)
                                @php
                                    $rLabels = \App\Models\Permission::getRoles();
                                @endphp
                                <option value="{{ $r }}">{{ $rLabels[$r]['label'] ?? $r }}</option>
                            @endforeach
                        </select>
                        <div id="edit_role_help" class="form-text small"></div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                <button type="submit" class="btn btn-warning fw-bold"><i class="bi bi-save me-2"></i>Actualizar Datos</button>
            </div>
        </form>
    </div>
</div>

<style>
    .avatar-circle {
        width: 40px; height: 40px;
        border-radius: 50%;
        color: white;
        display: flex; align-items: center; justify-content: center;
        font-weight: bold; font-size: 18px;
        text-transform: uppercase;
    }
</style>

<script>
    function editUser(user) {
        document.getElementById('edit_name').value = user.name;
        document.getElementById('edit_email').value = user.email;
        document.getElementById('edit_role').value = user.role;
        document.getElementById('editUserForm').action = "{{ url('/users') }}/" + user.id;

        var roleHelp = document.getElementById('edit_role_help');
        var roleSelect = document.getElementById('edit_role');

        if (user.is_system_admin || user.role === 'superadmin') {
            roleSelect.value = 'superadmin';
            roleHelp.innerHTML = '<span class="text-danger"><i class="bi bi-shield-lock-fill me-1"></i>Cuenta de Sistema protegida. Rol bloqueado.</span>';
            @if(!$currentUser->isSuperAdmin())
                roleSelect.disabled = true;
            @endif
        } else {
            roleHelp.innerHTML = '';
            roleSelect.disabled = false;
        }

        new bootstrap.Modal(document.getElementById('editUserModal')).show();
    }
</script>
@endsection
