@extends('layouts.app')

@section('content')
<div class="container py-4">
    <div class="row justify-content-center">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-gradient bg-warning text-dark border-0 py-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="d-flex align-items-center">
                            <i class="bi bi-building-gear fs-4 me-3"></i>
                            <div>
                                <h5 class="mb-0 fw-bold">Editar Empresa #{{ $company->id }}</h5>
                                <small class="opacity-75">{{ $company->name }}</small>
                            </div>
                        </div>
                        <a href="{{ route('admin_fit.super_admin.companies.index') }}" class="btn btn-sm btn-dark">
                            <i class="bi bi-chevron-left"></i> Volver
                        </a>
                    </div>
                </div>
                <div class="card-body">
                    @if(session('success'))
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="bi bi-check-circle me-2"></i>
                            {{ session('success') }}
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    @endif

                    @if($errors->any())
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="bi bi-exclamation-triangle me-2"></i>
                            <ul class="mb-0">
                                @foreach($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    @endif

                    {{-- Sección 1: Datos de la Empresa --}}
                    <div class="mb-5">
                        <h6 class="text-muted text-uppercase small fw-bold mb-3">
                            <i class="bi bi-info-circle me-2"></i>Datos de la Empresa
                        </h6>

                        <form method="POST" action="{{ route('admin_fit.super_admin.companies.update', $company) }}">
                            @csrf
                            @method('PUT')

                            <div class="row g-3">
                                <div class="col-12">
                                    <label for="name" class="form-label">Nombre <span class="text-danger">*</span></label>
                                    <input type="text" id="name" name="name" class="form-control @error('name') is-invalid @enderror" value="{{ old('name', $company->name) }}" required>
                                    @error('name')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="col-12 col-md-6">
                                    <label for="email" class="form-label">Email</label>
                                    <input type="email" id="email" name="email" class="form-control @error('email') is-invalid @enderror" value="{{ old('email', $company->email) }}">
                                    @error('email')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="col-12 col-md-6">
                                    <label for="phone" class="form-label">Teléfono</label>
                                    <input type="text" id="phone" name="phone" class="form-control @error('phone') is-invalid @enderror" value="{{ old('phone', $company->phone) }}">
                                    @error('phone')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="col-12">
                                    <label for="address" class="form-label">Dirección</label>
                                    <textarea id="address" name="address" class="form-control @error('address') is-invalid @enderror" rows="3">{{ old('address', $company->address) }}</textarea>
                                    @error('address')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                            <div class="d-flex justify-content-end gap-2 mt-3">
                                <button type="submit" class="btn btn-warning">
                                    <i class="bi bi-check-circle me-1"></i> Actualizar Datos
                                </button>
                            </div>
                        </form>
                    </div>

                    <hr class="my-4">

                    {{-- Sección 2: Usuarios Asignados --}}
                    <div class="mb-5">
                        <h6 class="text-muted text-uppercase small fw-bold mb-3">
                            <i class="bi bi-people me-2"></i>Usuarios Asignados ({{ count($users) }})
                        </h6>

                        @if(count($users) > 0)
                            <div class="table-responsive">
                                <table class="table table-hover align-middle">
                                    <thead class="table-light">
                                        <tr>
                                            <th>ID</th>
                                            <th>Nombre</th>
                                            <th>Email</th>
                                            <th>Teléfono</th>
                                            <th>Estado</th>
                                            <th>Asignado</th>
                                            <th class="text-center">Acciones</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @foreach($users as $user)
                                            <tr>
                                                <td>{{ $user['id'] }}</td>
                                                <td>{{ $user['name'] }}</td>
                                                <td>{{ $user['email'] }}</td>
                                                <td>{{ $user['phone'] ?? '-' }}</td>
                                                <td>
                                                    @if($user['status'])
                                                        <span class="badge bg-success">Activo</span>
                                                    @else
                                                        <span class="badge bg-secondary">Inactivo</span>
                                                    @endif
                                                </td>
                                                <td>{{ $user['assigned_at'] }}</td>
                                                <td class="text-center">
                                                    <button type="button" class="btn btn-sm btn-outline-danger btn-remove-user" data-user-id="{{ $user['id'] }}" data-user-name="{{ $user['name'] }}">
                                                        <i class="bi bi-person-dash"></i> Remover
                                                    </button>
                                                </td>
                                            </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                            </div>
                        @else
                            <div class="alert alert-info">
                                <i class="bi bi-info-circle me-2"></i>
                                Esta empresa no tiene usuarios asignados.
                            </div>
                        @endif
                    </div>

                    <hr class="my-4">

                    {{-- Sección 3: Asignar Nuevo Usuario --}}
                    <div>
                        <h6 class="text-muted text-uppercase small fw-bold mb-3">
                            <i class="bi bi-person-plus me-2"></i>Asignar Nuevo Usuario
                        </h6>

                        @if(count($unassignedUsers) > 0)
                            <form method="POST" action="{{ route('admin_fit.super_admin.companies.assign_user', $company) }}">
                                @csrf

                                <div class="row g-3 align-items-end">
                                    <div class="col-12 col-md-8">
                                        <label for="user_id" class="form-label">Seleccionar Usuario</label>
                                        <select id="user_id" name="user_id" class="form-select @error('user_id') is-invalid @enderror" required>
                                            <option value="">Seleccione un usuario...</option>
                                            @foreach($unassignedUsers as $user)
                                                <option value="{{ $user->id }}">{{ $user->name }} ({{ $user->email }})</option>
                                            @endforeach
                                        </select>
                                        @error('user_id')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>

                                    <div class="col-12 col-md-4">
                                        <button type="submit" class="btn btn-success w-100">
                                            <i class="bi bi-person-plus me-1"></i> Asignar Usuario
                                        </button>
                                    </div>
                                </div>
                            </form>
                        @else
                            <div class="alert alert-info">
                                <i class="bi bi-info-circle me-2"></i>
                                No hay usuarios disponibles para asignar. Todos los usuarios ya están asignados a alguna empresa.
                            </div>
                        @endif
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.btn-remove-user').forEach(btn => {
        btn.addEventListener('click', function() {
            const userId = this.dataset.userId;
            const userName = this.dataset.userName;
            const companyId = {{ $company->id }};
            
            Swal.fire({
                title: '¿Remover usuario?',
                html: `Se removerá al usuario <strong>${userName}</strong> de esta empresa.`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc3545',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Sí, remover',
                cancelButtonText: 'Cancelar'
            }).then((result) => {
                if (result.isConfirmed) {
                    const form = document.createElement('form');
                    form.method = 'POST';
                    form.action = `/admin-fit/super-admin/companies/${companyId}/remove-user/${userId}`;
                    
                    const csrfInput = document.createElement('input');
                    csrfInput.type = 'hidden';
                    csrfInput.name = '_token';
                    csrfInput.value = document.querySelector('meta[name="csrf-token"]').content;
                    form.appendChild(csrfInput);
                    
                    const methodInput = document.createElement('input');
                    methodInput.type = 'hidden';
                    methodInput.name = '_method';
                    methodInput.value = 'DELETE';
                    form.appendChild(methodInput);
                    
                    document.body.appendChild(form);
                    form.submit();
                }
            });
        });
    });
});
</script>
@endpush
@endsection
