import 'dart:io'; import 'package:equatable/equatable.dart'; import 'package:flutter/foundation.dart'; // Per kIsWeb import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flux/core/blocs/session/session_cubit.dart'; import 'package:flux/features/company/data/company_repository.dart'; import 'package:flux/features/company/models/company_model.dart'; import 'package:get_it/get_it.dart'; import 'package:image_picker/image_picker.dart'; part 'company_settings_state.dart'; class CompanySettingsCubit extends Cubit { final CompanyRepository _repository = GetIt.I(); final SessionCubit _sessionCubit = GetIt.I(); CompanySettingsCubit() : super(const CompanySettingsState()); void initSettings() { final currentCompany = _sessionCubit.state.company; if (currentCompany != null) { emit( state.copyWith( company: currentCompany, status: CompanySettingsStatus.ready, ), ); } } void updateFields({ String? name, String? vatId, String? address, String? city, String? zipCode, String? phone, String? email, }) { if (state.company == null) return; final updated = state.company!.copyWith( name: name ?? state.company!.name, vatId: vatId ?? state.company!.vatId, address: address ?? state.company!.address, city: city ?? state.company!.city, zipCode: zipCode ?? state.company!.zipCode, phone: phone ?? state.company!.phone, email: email ?? state.company!.email, ); emit(state.copyWith(company: updated)); } Future saveSettings() async { if (state.company == null) return; emit( state.copyWith(status: CompanySettingsStatus.saving, errorMessage: null), ); try { // 1. Salva i dati su Supabase final updatedCompany = await _repository.updateCompany(state.company!); // 2. Aggiorna la sessione globale per riflettere i cambiamenti in tutta l'app _sessionCubit.updateCurrentCompany(updatedCompany); emit( state.copyWith( status: CompanySettingsStatus.success, company: updatedCompany, ), ); } catch (e) { emit( state.copyWith( status: CompanySettingsStatus.failure, errorMessage: e.toString(), ), ); } } // Metodo per gestire l'upload del logo Future uploadLogo(Uint8List bytes, String fileName) async { if (state.company == null) return; emit(state.copyWith(status: CompanySettingsStatus.uploadingLogo)); try { // Usa il tuo repository per caricare il file nel bucket 'company_logos' // Il file può essere Uint8List (se sei su Web) o File (se sei su Mobile/Desktop) final publicUrl = await _repository.uploadCompanyLogo( companyId: state.company!.id!, fileBytes: bytes, fileName: fileName, ); final updatedCompany = state.company!.copyWith(logoUrl: publicUrl); emit( state.copyWith( company: updatedCompany, status: CompanySettingsStatus.ready, ), ); // Chiamiamo il salvataggio per rendere definitivo l'URL nel record della compagnia await saveSettings(); } catch (e) { emit( state.copyWith( status: CompanySettingsStatus.failure, errorMessage: "Errore caricamento logo: $e", ), ); } } }