ALTER TABLE `sesiones`
ADD COLUMN `aprobado`  varchar(10) NULL DEFAULT 'aprobado' AFTER `updated_at`;

ALTER TABLE `sesiones`
MODIFY COLUMN `aprobado`  varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'aprobado' AFTER `updated_at`;


ALTER TABLE `tratamientos`
MODIFY COLUMN `iva`  varchar(2) NOT NULL AFTER `tiene_iva`;

ALTER TABLE `horarios`
ADD COLUMN `created_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `modificado_por`,
ADD COLUMN `updated_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `created_at`;






ALTER TABLE `users`
ADD COLUMN `uuid`  text NULL AFTER `nota`;

-- 2024

ALTER TABLE `productos`
ADD COLUMN `created_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `modificado_por`,
ADD COLUMN `updated_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `created_at`;

ALTER TABLE `marcas`
ADD COLUMN `created_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `estatus`,
ADD COLUMN `updated_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `created_at`;


-- ALTER TABLE `productos`
-- MODIFY COLUMN `iva`  varchar(2) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '16' AFTER `tiene_iva`;

ALTER TABLE `productos`
MODIFY COLUMN `iva`  varchar(2) NOT NULL DEFAULT '16' AFTER `tiene_iva`,
MODIFY COLUMN `ieps`  varchar(2) NOT NULL AFTER `tiene_ieps`;

ALTER TABLE `productos`
ADD COLUMN `path`  text NULL AFTER `updated_at`;

-- checar las imagenes de los productos si se cargan y eliminan
-- https://laravel.com/docs/master/filesystem#the-public-disk para carga de archivo en el servidor y mostrar
-- eliminar imagenes  en storoge/app/public/images/productos

CREATE TABLE `tiendas` (
`id`  int NOT NULL AUTO_INCREMENT ,
`producto_id`  int NULL ,
`user_id`  bigint(11) UNSIGNED NULL ,
`cantidad`  numeric NULL ,
`created_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP ,
`updated_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP ,
PRIMARY KEY (`id`)
);

ALTER TABLE `tiendas` ADD CONSTRAINT `tiendas_producto_id` FOREIGN KEY (`producto_id`) REFERENCES `productos` (`id`);
ALTER TABLE `tiendas` ADD CONSTRAINT `tiendas_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);

ALTER TABLE `productos_bajas`
ADD COLUMN `created_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `modificado_por`,
ADD COLUMN `updated_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `created_at`;

ALTER TABLE `ingresos_mercancias`
ADD COLUMN `created_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `modificado_por`,
ADD COLUMN `updated_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `created_at`;

ALTER TABLE `ingresos_mercancias`
ADD COLUMN `observacion`  text NULL AFTER `updated_at`;

ALTER TABLE `traspasos_mercancias`
ADD COLUMN `created_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `modificado_por`,
ADD COLUMN `updated_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `created_at`;

ALTER TABLE `inventarios`
ADD COLUMN `created_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `modificado_por`,
ADD COLUMN `updated_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `created_at`;


ALTER TABLE `inventarios`
DROP COLUMN `codigo_barras`,
DROP COLUMN `nombre`,
DROP COLUMN `descripcion`,
DROP COLUMN `precio`;

ALTER TABLE `almacenes` DROP FOREIGN KEY `almacenes_sucursal_id`;
ALTER TABLE `productos_bajas` DROP FOREIGN KEY `productos_bajas_almacen_id`;
ALTER TABLE `productos_bajas` ADD CONSTRAINT `productos_bajas_almacen_id` FOREIGN KEY (`almacen_id`) REFERENCES `sucursales` (`id`);
ALTER TABLE `productos_bajas` DROP FOREIGN KEY `productos_bajas_almacen_id`;
ALTER TABLE `productos_bajas` CHANGE COLUMN `almacen_id` `sucursal_id`  int(11) NOT NULL AFTER `tipo_baja_id`;
ALTER TABLE `productos_bajas` ADD CONSTRAINT `productos_bajas_sucursal_id` FOREIGN KEY (`sucursal_id`) REFERENCES `sucursales` (`id`);

ALTER TABLE `ingresos_mercancias` CHANGE COLUMN `almacen_id` `sucursal_id`  int(11) NOT NULL AFTER `id`;
ALTER TABLE `ingresos_mercancias` DROP FOREIGN KEY `ingresos_mercancias_almacen_id`;
ALTER TABLE `ingresos_mercancias` ADD CONSTRAINT `ingresos_mercancias_sucursal_id` FOREIGN KEY (`sucursal_id`) REFERENCES `sucursales` (`id`);

ALTER TABLE `inventarios` DROP FOREIGN KEY `inventarios_almacen_id`;
ALTER TABLE `inventarios` CHANGE COLUMN `almacen_id` `sucursal_id`  int(11) NOT NULL AFTER `producto_id`;
ALTER TABLE `inventarios` ADD CONSTRAINT `inventarios_sucursal_id` FOREIGN KEY (`sucursal_id`) REFERENCES `sucursales` (`id`);

ALTER TABLE `traspasos_mercancias` DROP FOREIGN KEY `traspasos_mercancias_almacen_destino_id`;
ALTER TABLE `traspasos_mercancias` DROP FOREIGN KEY `traspasos_mercancias_almacen_origen_id`;
ALTER TABLE `traspasos_mercancias` CHANGE COLUMN `almacen_origen_id` `sucursal_origen_id`  int(11) NOT NULL AFTER `id`,
CHANGE COLUMN `almacen_destino_id` `sucursal_destino_id`  int(11) NOT NULL AFTER `sucursal_origen_id`;
ALTER TABLE `traspasos_mercancias` ADD CONSTRAINT `traspasos_mercancias_sucursal_destino_id` FOREIGN KEY (`sucursal_destino_id`) REFERENCES `sucursales` (`id`);
ALTER TABLE `traspasos_mercancias` ADD CONSTRAINT `traspasos_mercancias_sucursal_origen_id` FOREIGN KEY (`sucursal_origen_id`) REFERENCES `sucursales` (`id`);

Drop table almacenes;

insert into tipos_bajas(descripcion) values("Por uso");
insert into tipos_bajas(descripcion) values("Por perdida");


-- instalacion par QR
-- https://www.npmjs.com/package/qrcode-vue3


ALTER TABLE `vales` DROP FOREIGN KEY `vales_venta_id`;
ALTER TABLE `vales` DROP COLUMN `venta_id`;
ALTER TABLE `ventas_tratamientos` DROP FOREIGN KEY `ventas_tratamientos_venta_id`;
ALTER TABLE `ventas_detalles`
MODIFY COLUMN `producto_id`  int(11) NULL AFTER `venta_id`,
ADD COLUMN `tratamiento_id`  int NULL AFTER `producto_id`,
ADD COLUMN `vale_id`  int NULL AFTER `tratamiento_id`;
ALTER TABLE `ventas_detalles`
MODIFY COLUMN `vale_id`  bigint(20) UNSIGNED NULL DEFAULT NULL AFTER `tratamiento_id`;
ALTER TABLE `ventas_detalles` ADD CONSTRAINT `ventas_detalles_tratamiento_id` FOREIGN KEY (`tratamiento_id`) REFERENCES `tratamientos` (`id`);
ALTER TABLE `ventas_detalles` ADD CONSTRAINT `ventas_detalles_vale_id` FOREIGN KEY (`vale_id`) REFERENCES `vales` (`id`);
Drop table ventas_tratamientos;
ALTER TABLE `ventas`
MODIFY COLUMN `cliente_id`  int(11) NULL AFTER `sucursal_id`;


CREATE TABLE `ventas_sesiones` (
`id`  bigint UNSIGNED NOT NULL AUTO_INCREMENT ,
`sesion_id`  bigint(20) UNSIGNED NOT NULL ,
`venta_id`  bigint(20) UNSIGNED NOT NULL ,
`created_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP ,
`updated_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP ,
PRIMARY KEY (`id`),
KEY `ventas_sesiones_sesion_id` (`sesion_id`),
KEY `ventas_sesiones_venta_id` (`venta_id`),
CONSTRAINT `ventas_sesiones_sesion_id` FOREIGN KEY (`sesion_id`) REFERENCES `sesiones` (`id`),
CONSTRAINT `ventas_sesiones_venta_id` FOREIGN KEY (`venta_id`) REFERENCES `ventas` (`id`)
);

ALTER TABLE `vales_sessiones`
CHANGE COLUMN `session_id` `sesion_id`  bigint(20) UNSIGNED NOT NULL AFTER `vale_id`;

ALTER TABLE `ventas`
ADD COLUMN `created_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `es_credito`,
ADD COLUMN `updated_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `created_at`;

ALTER TABLE `ventas_detalles`
ADD COLUMN `created_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `modificado_por`,
ADD COLUMN `updated_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `created_at`;

ALTER TABLE `ventas_cortes`
ADD COLUMN `created_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `corte_caja_id`,
ADD COLUMN `updated_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `created_at`;

ALTER TABLE `vales`
ADD COLUMN `created_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `modificado_por`,
ADD COLUMN `updated_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `created_at`;

ALTER TABLE `ventas_detalles`
ADD COLUMN `descripcion`  varchar(100) NULL AFTER `id`;

ALTER TABLE `ventas`
MODIFY COLUMN `timbrador_id`  int(11) NULL AFTER `cliente_id`;

ALTER TABLE `pagos`
ADD COLUMN `created_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `total`,
ADD COLUMN `updated_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `created_at`;

insert into tipos_pagos(descripcion) values('Efectivo');
insert into tipos_pagos(descripcion) values('Tarjeta de debito');
insert into tipos_pagos(descripcion) values('Tarjeta de credito');
insert into tipos_pagos(descripcion) values('Credito');

ALTER TABLE `pagos`
ADD COLUMN `cambio`  double(11,6) NULL AFTER `tipo_pago_id`,
ADD COLUMN `pago`  double(11,6) NULL AFTER `cambio`;

ALTER TABLE `ventas`
CHANGE COLUMN `eps` `ieps`  float(9,2) NULL DEFAULT 0 AFTER `iva`;

ALTER TABLE `tratamientos`
MODIFY COLUMN `iva`  float(9,2) NOT NULL DEFAULT 0 AFTER `tiene_iva`,
MODIFY COLUMN `ieps`  float(9,2) NOT NULL DEFAULT 0 AFTER `tiene_ieps`;

CREATE UNIQUE INDEX sessionesid ON sesiones(id);


ALTER TABLE `ventas_detalles`
CHANGE COLUMN `eps` `ieps`  float(9,2) NULL DEFAULT 0 AFTER `iva`;


ALTER TABLE `vales`
MODIFY COLUMN `imagen_qr`  text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL AFTER `precio_unitario`;

ALTER TABLE `vales`
MODIFY COLUMN `vigencia`  datetime NULL AFTER `token`;

ALTER TABLE `productos`
ADD COLUMN `nombre_corto`  varchar(60) NULL AFTER `nombre`;

ALTER TABLE `ventas`
ADD COLUMN `observacion_cancelado`  text NULL AFTER `updated_at`;

ALTER TABLE `cortes_cajas`
ADD COLUMN `created_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `modificado_por`,
ADD COLUMN `updated_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `created_at`;

ALTER TABLE `cortes_cajas`
ADD COLUMN `fecha_inicio`  datetime NULL AFTER `updated_at`,
ADD COLUMN `fecha_fin`  datetime NULL AFTER `fecha_inicio`;

ALTER TABLE `cortes_cajas`
CHANGE COLUMN `total_tarjera_credito` `total_tarjeta_credito`  double(11,6) NOT NULL DEFAULT 0.000000 AFTER `total_tarjeta_debito`;

ALTER TABLE `sesiones`
ADD COLUMN `vale_id`  bigint(20) UNSIGNED NULL AFTER `user_id`;


ALTER TABLE `clientes`
ADD COLUMN `observacion`  text NULL AFTER `updated_at`;

ALTER TABLE `sesiones`
ADD COLUMN `observacion_cliente`  text NULL AFTER `updated_at`;


update tipos_pagos set estatus='inactivo' where id=4;


INSERT into tratamientos(id,tratamientos,precio) values(369,'Sin especificar',0);


-- nuevos cambios

ALTER TABLE `users`
ADD COLUMN `telefono`  varchar(60) NULL AFTER `email`,
ADD COLUMN `tipo_cliente`  varchar(60) NULL AFTER `email`;

ALTER TABLE `clientes`
ADD COLUMN `tipo`  varchar(60) NULL AFTER `email`;


CREATE TABLE `tipos_productos` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `descripcion` varchar(500) NOT NULL,
  `estatus` varchar(10) NOT NULL DEFAULT 'activo',
  PRIMARY KEY (`id`)
);

ALTER TABLE `tipos_productos`
ADD COLUMN `created_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `estatus`,
ADD COLUMN `updated_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `created_at`;

CREATE TABLE `tipos_servicios` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `descripcion` varchar(500) NOT NULL,
  `estatus` varchar(10) NOT NULL DEFAULT 'activo',
  PRIMARY KEY (`id`)
);

ALTER TABLE `tipos_servicios`
ADD COLUMN `created_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `estatus`,
ADD COLUMN `updated_at`  timestamp NULL ON UPDATE CURRENT_TIMESTAMP AFTER `created_at`;

ALTER TABLE `productos`
ADD COLUMN `tipo_producto_id`  int(11) NULL AFTER `estatus`,
ADD COLUMN `tipo_servicio_id`  int(11) NULL AFTER `estatus`;

ALTER TABLE `productos`
ADD CONSTRAINT `productos_tipo_producto_id` FOREIGN KEY (`tipo_producto_id`) REFERENCES `clinica_spa_laravel.`.`tipos_productos` (`id`),
ADD CONSTRAINT `productos_tipo_servicio_id` FOREIGN KEY (`tipo_servicio_id`) REFERENCES `clinica_spa_laravel.`.`tipos_servicios` (`id`);

--nuevo
ALTER TABLE ventas_detalles
DROP FOREIGN KEY ventas_detalles_venta_id;

-- Tabla de direcciones de entrega
CREATE TABLE direcciones_entrega (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    cliente_id int NOT NULL,
    nombre VARCHAR(255) NULL,
    calle VARCHAR(255) NOT NULL,
    numero_exterior VARCHAR(255) NOT NULL,
    numero_interior VARCHAR(255) NULL,
    colonia VARCHAR(255) NOT NULL,
    codigo_postal VARCHAR(255) NOT NULL,
    ciudad VARCHAR(255) NOT NULL,
    estado VARCHAR(255) NOT NULL,
    pais VARCHAR(255) DEFAULT 'México',
    referencia TEXT NULL,
    es_principal ENUM('si', 'no') DEFAULT 'no',
    estatus ENUM('activo', 'inactivo') DEFAULT 'activo',
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    deleted_at TIMESTAMP NULL,
    FOREIGN KEY (cliente_id) REFERENCES clientes(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Tabla de datos fiscales
CREATE TABLE datos_fiscales (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    cliente_id int NOT NULL,
    rfc VARCHAR(255) NOT NULL,
    razon_social VARCHAR(255) NOT NULL,
    regimen_fiscal VARCHAR(255) NULL,
    calle VARCHAR(255) NULL,
    numero_exterior VARCHAR(255) NULL,
    numero_interior VARCHAR(255) NULL,
    colonia VARCHAR(255) NULL,
    codigo_postal VARCHAR(255) NULL,
    ciudad VARCHAR(255) NULL,
    estado VARCHAR(255) NULL,
    pais VARCHAR(255) DEFAULT 'México',
    documento_fiscal VARCHAR(255) NULL,
    es_principal ENUM('si', 'no') DEFAULT 'no',
    estatus ENUM('activo', 'inactivo') DEFAULT 'activo',
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    deleted_at TIMESTAMP NULL,
    FOREIGN KEY (cliente_id) REFERENCES clientes(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Crear la tabla de bancos
CREATE TABLE bancos (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    nombre VARCHAR(255) NOT NULL UNIQUE,
    estatus ENUM('activo', 'inactivo') DEFAULT 'activo',
    created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Insertar la lista de bancos
INSERT INTO bancos (nombre) VALUES
('AFIRME'),
('ATLÁNTICO'),
('AZTECA'),
('BANAMEX'),
('BANBAJÍO'),
('BANCOPPEL'),
('BANORTE'),
('BANREGIO'),
('BBVA BANCOMER'),
('COMPARTAMOS'),
('CONFÍA'),
('HSBC'),
('INBURSA'),
('INTERBANCO'),
('MULTIVA'),
('PRONORTE'),
('SANTANDER'),
('SCOTIABANK'),
('UNIÓN');

CREATE TABLE opciones_pago_transferencia (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    banco VARCHAR(255) NOT NULL,
    titular VARCHAR(500) NOT NULL,
    clabe VARCHAR(18) NOT NULL,
    cuenta VARCHAR(20) NOT NULL,
    estatus ENUM('activo', 'inactivo') DEFAULT 'activo',
    created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

ALTER TABLE `ventas`
ADD COLUMN `opcion_pago_transferencia_id`  int(11) unsigned NULL AFTER `updated_at`,
ADD COLUMN `comprobante_pago`  text NULL AFTER `opcion_pago_transferencia_id`;

insert into opciones_pago_transferencia(banco,titular,clabe,cuenta) values('AFIRME','Juan Perez','123456789012345678','123456789012345678');

INSERT INTO clientes (rfc, razonSocial, estatus) VALUES ('XAXX010101000', 'General', 'inactivo');


-- -- Desactivar las restricciones de clave foránea temporalmente
SET FOREIGN_KEY_CHECKS = 0;

-- Truncar las tablas
TRUNCATE TABLE vales_sessiones;
TRUNCATE TABLE ventas_detalles;
TRUNCATE TABLE ventas_sesiones;
TRUNCATE TABLE pagos;
TRUNCATE TABLE ventas_cortes;
TRUNCATE TABLE cortes_cajas;
TRUNCATE TABLE ventas;
TRUNCATE TABLE vales;

-- Volver a activar las restricciones
SET FOREIGN_KEY_CHECKS = 1;

-- nuevo

ALTER TABLE `ventas`
ADD COLUMN `direccion_id`  bigint unsigned NULL AFTER `comprobante_pago`,
ADD COLUMN `datos_fiscales_id`  bigint unsigned NULL AFTER `direccion_id`,
ADD COLUMN `es_pago_tienda`  enum('si','no') NULL DEFAULT 'si' AFTER `datos_fiscales_id`,
ADD COLUMN `es_tienda_online`  enum('si','no') NULL DEFAULT 'no' AFTER `es_pago_tienda`;

ALTER TABLE `opciones_pago_transferencia`
ADD COLUMN `es_principal`  enum('si','no') NULL DEFAULT 'no' AFTER `estatus`;

UPDATE opciones_pago_transferencia set es_principal='si';

-- 16-08-2025

CREATE TABLE envios (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    venta_id BIGINT UNSIGNED NOT NULL,
    paqueteria VARCHAR(100) NOT NULL,
    numero_guia VARCHAR(100) DEFAULT NULL,
    fecha_envio DATETIME DEFAULT CURRENT_TIMESTAMP,
    fecha_entrega_estimada DATE DEFAULT NULL,
    estatus VARCHAR(50) DEFAULT 'Procesando',
    FOREIGN KEY (venta_id) REFERENCES ventas(id)
);

-- Tabla de configuración de impresiones
CREATE TABLE config_impresiones (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    nombre VARCHAR(100) NOT NULL,
    tipo_impresion ENUM('ticket', 'vale', 'datos_compra') NOT NULL DEFAULT 'ticket',
    ancho_papel INT DEFAULT 80 COMMENT 'Ancho en mm',
    alto_papel INT DEFAULT 0 COMMENT 'Alto en mm (0 = auto)',
    margen_superior DECIMAL(3,1) DEFAULT 0 COMMENT 'Margen superior en mm',
    margen_inferior DECIMAL(3,1) DEFAULT 0 COMMENT 'Margen inferior en mm',
    margen_izquierdo DECIMAL(3,1) DEFAULT 0 COMMENT 'Margen izquierdo en mm',
    margen_derecho DECIMAL(3,1) DEFAULT 0 COMMENT 'Margen derecho en mm',
    fuente_principal VARCHAR(50) DEFAULT 'Arial',
    tamano_fuente_principal INT DEFAULT 22 COMMENT 'Tamaño en px',
    tamano_fuente_titulo INT DEFAULT 28 COMMENT 'Tamaño en px',
    tamano_fuente_subtitulo INT DEFAULT 26 COMMENT 'Tamaño en px',
    tamano_fuente_detalle INT DEFAULT 20 COMMENT 'Tamaño en px',
    color_texto VARCHAR(7) DEFAULT '#000000',
    peso_fuente ENUM('normal', 'bold', 'lighter', 'bolder') DEFAULT 'bold',
    interlineado DECIMAL(3,1) DEFAULT 1.5,
    alineacion_titulo ENUM('left', 'center', 'right') DEFAULT 'center',
    alineacion_texto ENUM('left', 'center', 'right') DEFAULT 'center',
    alineacion_empresa ENUM('left', 'center', 'right') DEFAULT 'center',
    alineacion_direccion ENUM('left', 'center', 'right') DEFAULT 'center',
    alineacion_folio_fecha ENUM('left', 'center', 'right') DEFAULT 'center',
    alineacion_total ENUM('left', 'center', 'right') DEFAULT 'center',
    alineacion_footer ENUM('left', 'center', 'right') DEFAULT 'center',
    mostrar_logo BOOLEAN DEFAULT TRUE,
    mostrar_fecha BOOLEAN DEFAULT TRUE,
    mostrar_hora BOOLEAN DEFAULT TRUE,
    mostrar_cliente BOOLEAN DEFAULT TRUE,
    mostrar_empleado BOOLEAN DEFAULT TRUE,
    mostrar_observaciones BOOLEAN DEFAULT TRUE,
    separador_lineas VARCHAR(10) DEFAULT '---',
    padding_celda DECIMAL(3,1) DEFAULT 2 COMMENT 'Padding en mm',
    ancho_tabla INT DEFAULT 100 COMMENT 'Ancho de tabla en %',
    es_activa BOOLEAN DEFAULT FALSE,
    es_predeterminada BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Agregar campos para sucursal_id y porcentajes de ancho
ALTER TABLE config_impresiones 
ADD COLUMN sucursal_id INT NULL AFTER id,
ADD COLUMN ancho_contenido_porcentaje INT DEFAULT 88 COMMENT 'Ancho del contenido en porcentaje',
ADD COLUMN ancho_cuerpo_porcentaje INT DEFAULT 80 COMMENT 'Ancho del body en porcentaje para impresión';

-- Agregar foreign key para sucursal_id
ALTER TABLE config_impresiones 
ADD CONSTRAINT config_impresiones_sucursal_id 
FOREIGN KEY (sucursal_id) REFERENCES sucursales(id);

-- Insertar configuración predeterminada
INSERT INTO config_impresiones (
    nombre, tipo_impresion, ancho_papel, alto_papel, margen_superior, margen_inferior, 
    margen_izquierdo, margen_derecho, fuente_principal, tamano_fuente_principal, 
    tamano_fuente_titulo, tamano_fuente_subtitulo, tamano_fuente_detalle, 
    color_texto, peso_fuente, interlineado, alineacion_titulo, alineacion_texto,
    alineacion_empresa, alineacion_direccion, alineacion_folio_fecha, alineacion_total, alineacion_footer,
    mostrar_logo, mostrar_fecha, mostrar_hora, mostrar_cliente, mostrar_empleado,
    mostrar_observaciones, separador_lineas, padding_celda, ancho_tabla,
    ancho_contenido_porcentaje, ancho_cuerpo_porcentaje, sucursal_id,
    es_activa, es_predeterminada
) VALUES (
    'Ticket Predeterminado', 'ticket', 58, 0, 0, 0, 0, 0, 'Arial', 12, 14, 12, 8,
    '#000000', 'bold', 1.5, 'center', 'center', 'center', 'center', 'center', 'center', 'center',
    TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, '---', 2, 98, 88, 80, NULL, TRUE, TRUE
);

-- Tabla de configuración de correos
CREATE TABLE config_correos (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    nombre VARCHAR(100) NOT NULL,
    correo_prueba VARCHAR(255) NOT NULL,
    modo_prueba BOOLEAN DEFAULT TRUE COMMENT 'Si está activo el modo prueba',
    es_activa BOOLEAN DEFAULT FALSE COMMENT 'Si esta configuración está activa',
    created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_activa_modo (es_activa, modo_prueba)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Insertar configuración predeterminada de correo
INSERT INTO config_correos (
    nombre, correo_prueba, modo_prueba, es_activa
) VALUES (
    'Configuración Predeterminada', 'deyvijesusgomezmoha@gmail.com', TRUE, TRUE
);

-- Agregar campos para impresión directa
ALTER TABLE config_impresiones 
ADD COLUMN es_impresion_directa BOOLEAN DEFAULT FALSE COMMENT 'Indica si será impresión directa',
ADD COLUMN ip_impresora VARCHAR(45) NULL COMMENT 'IP de la impresora para impresión directa',
ADD COLUMN ngrok_key VARCHAR(255) NULL COMMENT 'Key de ngrok para impresión directa';


ALTER TABLE config_impresiones
ADD COLUMN user_id INT NULL COMMENT 'usuario que puede imprimir';

-- Agregar campos adicionales a datos_fiscales
ALTER TABLE datos_fiscales
ADD COLUMN correo VARCHAR(255) NULL COMMENT 'Correo electrónico para facturación' AFTER razon_social,
ADD COLUMN uso_cfdi VARCHAR(10) NULL COMMENT 'Clave de uso de CFDI según catálogo SAT' AFTER correo,
ADD COLUMN regimen_fiscal VARCHAR(10) NULL COMMENT 'Clave de régimen fiscal según catálogo SAT' AFTER uso_cfdi,
ADD COLUMN metodo_pago VARCHAR(10) NULL COMMENT 'Método de pago según catálogo SAT' AFTER regimen_fiscal;

-- ============================================
-- CAMBIOS DE HOY - 2025-01-27
-- Modificación de relaciones de config_impresiones
-- Cambio de relación uno-a-muchos a muchos-a-muchos para sucursales y usuarios
-- ============================================

-- Crear tabla pivot para relación many-to-many entre config_impresiones y sucursales
CREATE TABLE IF NOT EXISTS config_impresion_sucursal (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    config_impresion_id INT UNSIGNED NOT NULL,
    sucursal_id INT NOT NULL,
    created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (config_impresion_id) REFERENCES config_impresiones(id) ON DELETE CASCADE,
    FOREIGN KEY (sucursal_id) REFERENCES sucursales(id) ON DELETE CASCADE,
    UNIQUE KEY unique_config_sucursal (config_impresion_id, sucursal_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Crear tabla pivot para relación many-to-many entre config_impresiones y users
CREATE TABLE IF NOT EXISTS config_impresion_user (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    config_impresion_id INT UNSIGNED NOT NULL,
    user_id BIGINT UNSIGNED NOT NULL,
    created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (config_impresion_id) REFERENCES config_impresiones(id) ON DELETE CASCADE,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    UNIQUE KEY unique_config_user (config_impresion_id, user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Migrar datos existentes de sucursal_id a la tabla pivot
INSERT INTO config_impresion_sucursal (config_impresion_id, sucursal_id)
SELECT id, sucursal_id 
FROM config_impresiones 
WHERE sucursal_id IS NOT NULL;

-- Migrar datos existentes de user_id a la tabla pivot
INSERT INTO config_impresion_user (config_impresion_id, user_id)
SELECT id, user_id 
FROM config_impresiones 
WHERE user_id IS NOT NULL;

-- Actualizar tipo_impresion para incluir 'etiquetas' y 'otros'
ALTER TABLE config_impresiones
MODIFY COLUMN tipo_impresion ENUM('ticket', 'vale', 'datos_compra', 'etiquetas', 'otros') NOT NULL DEFAULT 'ticket';

-- NOTA: Los campos sucursal_id y user_id se mantienen temporalmente para compatibilidad
-- pero se recomienda eliminarlos después de verificar que todo funciona correctamente
-- ALTER TABLE config_impresiones DROP FOREIGN KEY config_impresiones_sucursal_id;
-- ALTER TABLE config_impresiones DROP COLUMN sucursal_id;
-- ALTER TABLE config_impresiones DROP COLUMN user_id;

-- Agregar campo codigo_barras a productos si no existe
-- Nota: Ejecutar manualmente si el campo no existe
-- ALTER TABLE `productos` ADD COLUMN `codigo_barras` VARCHAR(45) NULL AFTER `marca_id`;

-- ============================================
-- 2026-02-28 - Reservar cita Cliente (pago transferencia)
-- Campos para que clientes seleccionen cuenta de transferencia y suban comprobante
-- ============================================

ALTER TABLE `sesiones`
ADD COLUMN `opcion_pago_transferencia_id` INT UNSIGNED NULL AFTER `vale_id`,
ADD COLUMN `comprobante_pago` TEXT NULL AFTER `opcion_pago_transferencia_id`;

ALTER TABLE `sesiones`
ADD CONSTRAINT `sesiones_opcion_pago_transferencia_id_foreign` 
FOREIGN KEY (`opcion_pago_transferencia_id`) REFERENCES `opciones_pago_transferencia` (`id`) ON DELETE SET NULL;

-- ============================================
-- 2026-03-22 - Fase 3: config_empresa + cancelación venta en línea (ver database/sql/cambios_pendientes.sql)
-- ============================================

-- ============================================
-- 2026-03-22 - Fase 4: citas — es_pago_cita / fecha_pago_cita_verificado (ver database/sql/cambios_pendientes.sql)
-- ============================================

-- ============================================
-- 2026-05-21 - Módulo de cotizaciones (persistencia, listado, conversión a venta)
-- ============================================

CREATE TABLE IF NOT EXISTS `cotizaciones` (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    `folio` VARCHAR(80) NOT NULL,
    `sucursal_id` INT NOT NULL,
    `cliente_id` INT NULL,
    `user_id` BIGINT UNSIGNED NULL,
    `total` DOUBLE(11,6) NOT NULL DEFAULT 0,
    `subtotal` DOUBLE(11,6) NOT NULL DEFAULT 0,
    `iva` DOUBLE(11,6) NOT NULL DEFAULT 0,
    `ieps` DOUBLE(11,6) NOT NULL DEFAULT 0,
    `estatus` ENUM('borrador','lista','convertida','cancelada') NOT NULL DEFAULT 'borrador',
    `venta_id` BIGINT UNSIGNED NULL,
    `observacion` TEXT NULL,
    `fecha_registro` DATETIME NULL,
    `created_at` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
    `updated_at` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    UNIQUE KEY `cotizaciones_folio_unique` (`folio`),
    KEY `cotizaciones_sucursal_id` (`sucursal_id`),
    KEY `cotizaciones_cliente_id` (`cliente_id`),
    KEY `cotizaciones_estatus` (`estatus`),
    KEY `cotizaciones_venta_id` (`venta_id`),
    CONSTRAINT `cotizaciones_sucursal_id` FOREIGN KEY (`sucursal_id`) REFERENCES `sucursales` (`id`),
    CONSTRAINT `cotizaciones_cliente_id` FOREIGN KEY (`cliente_id`) REFERENCES `clientes` (`id`),
    CONSTRAINT `cotizaciones_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL,
    CONSTRAINT `cotizaciones_venta_id` FOREIGN KEY (`venta_id`) REFERENCES `ventas` (`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `cotizaciones_detalles` (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    `cotizacion_id` BIGINT UNSIGNED NOT NULL,
    `descripcion` VARCHAR(255) NOT NULL,
    `producto_id` INT NULL,
    `tratamiento_id` INT NULL,
    `total` DOUBLE(11,6) NOT NULL DEFAULT 0,
    `subtotal` DOUBLE(11,6) NOT NULL DEFAULT 0,
    `precio_unitario` DOUBLE(11,6) NOT NULL DEFAULT 0,
    `cantidad` DOUBLE(11,6) NOT NULL DEFAULT 1,
    `iva` DOUBLE(11,6) NOT NULL DEFAULT 0,
    `ieps` DOUBLE(11,6) NOT NULL DEFAULT 0,
    `created_at` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
    `updated_at` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    KEY `cotizaciones_detalles_cotizacion_id` (`cotizacion_id`),
    CONSTRAINT `cotizaciones_detalles_cotizacion_id` FOREIGN KEY (`cotizacion_id`) REFERENCES `cotizaciones` (`id`) ON DELETE CASCADE,
    CONSTRAINT `cotizaciones_detalles_producto_id` FOREIGN KEY (`producto_id`) REFERENCES `productos` (`id`) ON DELETE SET NULL,
    CONSTRAINT `cotizaciones_detalles_tratamiento_id` FOREIGN KEY (`tratamiento_id`) REFERENCES `tratamientos` (`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ============================================
-- 2026-07-11 - Impresión térmica con cola y agente local (especificacion-impresion-cola.md)
-- A partir de aquí: actualización de BD para el nuevo sistema de impresión
-- ============================================

-- Puerto de red opcional en config_impresiones (default 9100 en aplicación)
ALTER TABLE `config_impresiones`
ADD COLUMN `puerto` SMALLINT UNSIGNED NULL DEFAULT 9100 COMMENT 'Puerto TCP impresora de red' AFTER `ip_impresora`;

-- Incluir ticket_cotizacion en enum si aún no existe
ALTER TABLE `config_impresiones`
MODIFY COLUMN `tipo_impresion` ENUM('ticket', 'ticket_cotizacion', 'vale', 'datos_compra', 'etiquetas', 'otros') NOT NULL DEFAULT 'ticket';

-- Cola de trabajos de impresión
CREATE TABLE IF NOT EXISTS `print_jobs` (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    `tipo` VARCHAR(50) NOT NULL COMMENT 'ticket_venta, ticket_cotizacion, ticket_prueba, ticket_vale',
    `estado` VARCHAR(20) NOT NULL DEFAULT 'pending' COMMENT 'pending, processing, completed, failed, cancelled',
    `venta_id` BIGINT UNSIGNED NULL,
    `config_impresion_id` INT UNSIGNED NULL,
    `sucursal_id` INT NULL,
    `user_id` BIGINT UNSIGNED NULL,
    `contenido` LONGTEXT NOT NULL,
    `codigo_barras` VARCHAR(100) NULL,
    `columnas` TINYINT UNSIGNED NOT NULL DEFAULT 42 COMMENT '32=58mm, 42=80mm',
    `impresora_snapshot` JSON NULL,
    `intentos` TINYINT UNSIGNED NOT NULL DEFAULT 0,
    `max_intentos` TINYINT UNSIGNED NOT NULL DEFAULT 3,
    `error_mensaje` TEXT NULL,
    `error_codigo` VARCHAR(50) NULL,
    `started_at` TIMESTAMP NULL,
    `completed_at` TIMESTAMP NULL,
    `created_at` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
    `updated_at` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    KEY `print_jobs_estado_created` (`estado`, `created_at`),
    KEY `print_jobs_sucursal_estado` (`sucursal_id`, `estado`),
    KEY `print_jobs_venta_id` (`venta_id`),
    CONSTRAINT `print_jobs_venta_id` FOREIGN KEY (`venta_id`) REFERENCES `ventas` (`id`) ON DELETE SET NULL,
    CONSTRAINT `print_jobs_config_impresion_id` FOREIGN KEY (`config_impresion_id`) REFERENCES `config_impresiones` (`id`) ON DELETE SET NULL,
    CONSTRAINT `print_jobs_sucursal_id` FOREIGN KEY (`sucursal_id`) REFERENCES `sucursales` (`id`) ON DELETE SET NULL,
    CONSTRAINT `print_jobs_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Tokens para agentes de impresión en PC de caja
CREATE TABLE IF NOT EXISTS `print_agent_tokens` (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    `nombre` VARCHAR(100) NOT NULL,
    `token_hash` VARCHAR(64) NOT NULL,
    `sucursal_id` INT NULL,
    `config_impresion_ids` JSON NULL COMMENT 'null o [] = todas las impresoras de la sucursal',
    `activo` TINYINT(1) NOT NULL DEFAULT 1,
    `last_seen_at` TIMESTAMP NULL,
    `created_at` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
    `updated_at` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    UNIQUE KEY `print_agent_tokens_token_hash_unique` (`token_hash`),
    KEY `print_agent_tokens_sucursal_id` (`sucursal_id`),
    CONSTRAINT `print_agent_tokens_sucursal_id` FOREIGN KEY (`sucursal_id`) REFERENCES `sucursales` (`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Permisos Spatie para impresión con cola
INSERT INTO `permissions` (`name`, `guard_name`, `created_at`, `updated_at`)
SELECT * FROM (
    SELECT 'impresion.imprimir' AS name, 'web' AS guard_name, NOW() AS created_at, NOW() AS updated_at
    UNION ALL SELECT 'impresion.reimprimir', 'web', NOW(), NOW()
    UNION ALL SELECT 'impresion.probar', 'web', NOW(), NOW()
    UNION ALL SELECT 'impresion.ver_cola', 'web', NOW(), NOW()
    UNION ALL SELECT 'impresion.gestionar_usuarios_impresora', 'web', NOW(), NOW()
) AS nuevos
WHERE NOT EXISTS (SELECT 1 FROM `permissions` p WHERE p.name = nuevos.name AND p.guard_name = 'web');

-- Asignar permisos de impresión a roles existentes (Administrador / Ventas / Gerente si existen)
INSERT INTO `role_has_permissions` (`permission_id`, `role_id`)
SELECT p.id, r.id
FROM `permissions` p
CROSS JOIN `roles` r
WHERE p.name IN ('impresion.imprimir', 'impresion.reimprimir', 'impresion.probar', 'impresion.ver_cola', 'impresion.gestionar_usuarios_impresora')
  AND r.name IN ('Administrador', 'Admin', 'Gerente', 'Ventas', 'Vendedor', 'Cajero')
  AND NOT EXISTS (
      SELECT 1 FROM `role_has_permissions` rhp
      WHERE rhp.permission_id = p.id AND rhp.role_id = r.id
  );

-- =============================================================================
-- 2026-08-17 — Foto de perfil de usuario (API app móvil; el SPA no la usa)
-- =============================================================================
ALTER TABLE `users`
ADD COLUMN `foto` VARCHAR(500) NULL DEFAULT NULL
    COMMENT 'Ruta relativa: public/images/usuarios/...'
    AFTER `telefono`;


