import 'dart:convert'; import 'dart:io' show Platform; import 'package:crypto/crypto.dart'; import 'package:path/path.dart'; import 'package:sqflite/sqflite.dart'; import 'package:sqflite_common_ffi/sqflite_ffi.dart'; import '../models/vendedor.dart'; import '../models/cliente.dart'; import '../models/producto.dart'; import '../models/pedido.dart'; import '../models/item_pedido.dart'; import '../models/ruta.dart'; import '../models/parada_ruta.dart'; class DatabaseHelper { static final DatabaseHelper _instance = DatabaseHelper._(); factory DatabaseHelper() => _instance; DatabaseHelper._(); static Database? _db; Future get database async { _db ??= await _initDB(); return _db!; } Future _initDB() async { if (Platform.isLinux || Platform.isWindows || Platform.isMacOS) { sqfliteFfiInit(); final dbPath = await databaseFactoryFfi.getDatabasesPath(); final path = join(dbPath, 'telcotronics.db'); return databaseFactoryFfi.openDatabase( path, options: OpenDatabaseOptions( version: 2, onCreate: _createTables, onUpgrade: _onUpgrade, ), ); } final dbPath = await getDatabasesPath(); final path = join(dbPath, 'telcotronics.db'); return openDatabase(path, version: 2, onCreate: _createTables, onUpgrade: _onUpgrade); } Future _onUpgrade(Database db, int oldVersion, int newVersion) async { if (oldVersion < 2) { await db.execute( "ALTER TABLE pedidos ADD COLUMN sync_estado TEXT NOT NULL DEFAULT 'PENDIENTE'"); } } Future _createTables(Database db, int version) async { await db.execute(''' CREATE TABLE usuarios ( id TEXT PRIMARY KEY, nombre TEXT NOT NULL, email TEXT NOT NULL UNIQUE, password TEXT NOT NULL, telefono TEXT, zona TEXT, avatar_initials TEXT ) '''); await db.execute(''' CREATE TABLE clientes ( id TEXT PRIMARY KEY, nombre TEXT NOT NULL, razon_social TEXT, direccion TEXT, telefono TEXT, nit TEXT, lat REAL DEFAULT 0, lng REAL DEFAULT 0, categoria TEXT DEFAULT 'Minorista' ) '''); await db.execute(''' CREATE TABLE productos ( id TEXT PRIMARY KEY, sku TEXT UNIQUE NOT NULL, nombre TEXT NOT NULL, descripcion TEXT, categoria TEXT, precio REAL NOT NULL, precio_mayorista REAL NOT NULL, unidad TEXT DEFAULT 'unidad', stock INTEGER DEFAULT 0, emoji TEXT DEFAULT '📦' ) '''); await db.execute(''' CREATE TABLE rutas ( id TEXT PRIMARY KEY, nombre TEXT NOT NULL, zona TEXT, fecha TEXT NOT NULL ) '''); await db.execute(''' CREATE TABLE paradas_ruta ( id TEXT PRIMARY KEY, ruta_id TEXT NOT NULL, cliente_id TEXT NOT NULL, orden INTEGER NOT NULL, estado TEXT NOT NULL DEFAULT 'pendiente', hora_estimada TEXT, hora_visita TEXT, notas_visita TEXT, FOREIGN KEY (ruta_id) REFERENCES rutas(id) ON DELETE CASCADE, FOREIGN KEY (cliente_id) REFERENCES clientes(id) ) '''); await db.execute(''' CREATE TABLE pedidos ( id TEXT PRIMARY KEY, cliente_id TEXT NOT NULL, estado TEXT NOT NULL DEFAULT 'pendiente', fecha TEXT NOT NULL, notas TEXT, firma_base64 TEXT, sync_estado TEXT NOT NULL DEFAULT 'PENDIENTE', FOREIGN KEY (cliente_id) REFERENCES clientes(id) ) '''); await db.execute(''' CREATE TABLE items_pedido ( id INTEGER PRIMARY KEY AUTOINCREMENT, pedido_id TEXT NOT NULL, producto_id TEXT NOT NULL, cantidad INTEGER NOT NULL, precio_unitario REAL NOT NULL, FOREIGN KEY (pedido_id) REFERENCES pedidos(id) ON DELETE CASCADE, FOREIGN KEY (producto_id) REFERENCES productos(id) ) '''); } // ── Usuarios ──────────────────────────────────────────────── static String _sha256(String input) => sha256.convert(utf8.encode(input)).toString(); Future insertUsuario(Vendedor v, String password) async { final db = await database; await db.insert('usuarios', {...v.toMap(), 'password': _sha256(password)}, conflictAlgorithm: ConflictAlgorithm.ignore); } /// Registra un usuario nuevo. Retorna false si el email ya existe. Future registerUsuario({ required String nombre, required String email, required String telefono, required String empresa, required String ruc, required String password, }) async { final db = await database; final exists = await db.query('usuarios', where: 'email = ?', whereArgs: [email.toLowerCase()]); if (exists.isNotEmpty) return false; final id = 'local_${DateTime.now().millisecondsSinceEpoch}'; await db.insert('usuarios', { 'id': id, 'nombre': nombre, 'email': email.toLowerCase(), 'telefono': telefono, 'zona': empresa, 'password': _sha256(password), }); return true; } Future?> loginUsuario(String email, String password) async { final db = await database; // Acepta hash SHA-256 o texto plano (compatibilidad con seeder viejo) final hash = _sha256(password); var rows = await db.query('usuarios', where: 'email = ? AND password = ?', whereArgs: [email, hash]); if (rows.isEmpty) { rows = await db.query('usuarios', where: 'email = ? AND password = ?', whereArgs: [email, password]); } return rows.isEmpty ? null : rows.first; } Future getVendedor(String id) async { final db = await database; final rows = await db.query('usuarios', where: 'id = ?', whereArgs: [id]); return rows.isEmpty ? null : Vendedor.fromMap(rows.first); } // ── Clientes ──────────────────────────────────────────────── Future> getClientes() async { final db = await database; final rows = await db.query('clientes', orderBy: 'nombre ASC'); return rows.map(Cliente.fromMap).toList(); } Future insertCliente(Cliente c) async { final db = await database; await db.insert('clientes', c.toMap(), conflictAlgorithm: ConflictAlgorithm.replace); } Future updateCliente(Cliente c) async { final db = await database; await db.update('clientes', c.toMap(), where: 'id = ?', whereArgs: [c.id]); } Future deleteCliente(String id) async { final db = await database; await db.delete('clientes', where: 'id = ?', whereArgs: [id]); } // ── Productos ──────────────────────────────────────────────── Future> getProductos() async { final db = await database; final rows = await db.query('productos', orderBy: 'categoria ASC, nombre ASC'); return rows.map(Producto.fromMap).toList(); } Future getProductoBySku(String sku) async { final db = await database; final rows = await db.query('productos', where: 'sku = ?', whereArgs: [sku], limit: 1); return rows.isEmpty ? null : Producto.fromMap(rows.first); } Future insertProducto(Producto p) async { final db = await database; await db.insert('productos', p.toMap(), conflictAlgorithm: ConflictAlgorithm.replace); } Future updateProducto(Producto p) async { final db = await database; await db.update('productos', p.toMap(), where: 'id = ?', whereArgs: [p.id]); } Future updateStock(String productoId, int nuevoStock) async { final db = await database; await db.update('productos', {'stock': nuevoStock}, where: 'id = ?', whereArgs: [productoId]); } // ── Rutas ──────────────────────────────────────────────────── Future getRutaIdHoy() async { final db = await database; final hoy = DateTime.now().toIso8601String().substring(0, 10); final rows = await db.query('rutas', where: "fecha LIKE ?", whereArgs: ['$hoy%']); return rows.isEmpty ? null : rows.first['id'] as String; } Future getRutaConParadas( String rutaId, Map clientesMap) async { final db = await database; final rutaRows = await db.query('rutas', where: 'id = ?', whereArgs: [rutaId]); if (rutaRows.isEmpty) return null; final r = rutaRows.first; final paradaRows = await db.query('paradas_ruta', where: 'ruta_id = ?', whereArgs: [rutaId], orderBy: 'orden ASC'); final paradas = paradaRows.map((row) { final cliente = clientesMap[row['cliente_id'] as String]; if (cliente == null) return null; return ParadaRuta( id: row['id'] as String, cliente: cliente, orden: row['orden'] as int, estado: EstadoParadaExt.fromString(row['estado'] as String), horaEstimada: row['hora_estimada'] as String? ?? '', horaVisita: row['hora_visita'] as String?, notasVisita: row['notas_visita'] as String?, ); }).whereType().toList(); return Ruta( id: r['id'] as String, nombre: r['nombre'] as String, zona: r['zona'] as String? ?? '', paradas: paradas, fecha: DateTime.parse(r['fecha'] as String), ); } Future insertRuta(Ruta ruta) async { final db = await database; await db.insert('rutas', ruta.toMap(), conflictAlgorithm: ConflictAlgorithm.replace); return ruta.id; } Future insertParada(ParadaRuta parada, String rutaId) async { final db = await database; await db.insert('paradas_ruta', parada.toMap(rutaId), conflictAlgorithm: ConflictAlgorithm.replace); } Future updateParadaEstado( String paradaId, String estado, String? horaVisita) async { final db = await database; await db.update( 'paradas_ruta', {'estado': estado, 'hora_visita': horaVisita}, where: 'id = ?', whereArgs: [paradaId], ); } Future deleteParada(String paradaId) async { final db = await database; await db.delete('paradas_ruta', where: 'id = ?', whereArgs: [paradaId]); } Future reordenarParadas(List paradas, String rutaId) async { final db = await database; final batch = db.batch(); for (int i = 0; i < paradas.length; i++) { batch.update('paradas_ruta', {'orden': i + 1}, where: 'id = ?', whereArgs: [paradas[i].id]); } await batch.commit(noResult: true); } // ── Pedidos ───────────────────────────────────────────────── Future> getPedidos( Map clientesMap, Map productosMap) async { final db = await database; final pedidoRows = await db.query('pedidos', orderBy: 'fecha DESC'); final pedidos = []; for (final row in pedidoRows) { final cliente = clientesMap[row['cliente_id'] as String]; if (cliente == null) continue; final itemRows = await db.query('items_pedido', where: 'pedido_id = ?', whereArgs: [row['id']]); final items = itemRows.map((ir) { final producto = productosMap[ir['producto_id'] as String]; if (producto == null) return null; return ItemPedido( dbId: ir['id'] as int?, producto: producto, cantidad: ir['cantidad'] as int, precioUnitario: (ir['precio_unitario'] as num).toDouble(), ); }).whereType().toList(); pedidos.add(Pedido( id: row['id'] as String, cliente: cliente, estado: EstadoPedidoExt.fromString(row['estado'] as String), fecha: DateTime.parse(row['fecha'] as String), notas: row['notas'] as String? ?? '', firmaBase64: row['firma_base64'] as String?, syncEstado: row['sync_estado'] as String? ?? 'PENDIENTE', items: items, )); } return pedidos; } Future insertPedido(Pedido pedido) async { final db = await database; await db.insert('pedidos', pedido.toMap(), conflictAlgorithm: ConflictAlgorithm.replace); for (final item in pedido.items) { await db.insert('items_pedido', item.toMap(pedido.id), conflictAlgorithm: ConflictAlgorithm.replace); } } Future updateEstadoPedido(String pedidoId, String estado) async { final db = await database; await db.update('pedidos', {'estado': estado}, where: 'id = ?', whereArgs: [pedidoId]); } Future updateSyncEstadoPedido(String pedidoId, String syncEstado) async { final db = await database; await db.update('pedidos', {'sync_estado': syncEstado}, where: 'id = ?', whereArgs: [pedidoId]); } Future updateFirmaPedido(String pedidoId, String firma) async { final db = await database; await db.update('pedidos', {'firma_base64': firma, 'estado': 'confirmado'}, where: 'id = ?', whereArgs: [pedidoId]); } Future deletePedido(String pedidoId) async { final db = await database; await db.delete('pedidos', where: 'id = ?', whereArgs: [pedidoId]); } // ── Utilidades ─────────────────────────────────────────────── Future isSeeded() async { final db = await database; final rows = await db.query('productos', limit: 1); return rows.isNotEmpty; } Future close() async => (await database).close(); }