SET NAMES utf8mb4;
SET time_zone = '-06:00';

CREATE TABLE IF NOT EXISTS planes (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  codigo VARCHAR(60) NOT NULL,
  nombre VARCHAR(120) NOT NULL,
  max_sucursales INT UNSIGNED NOT NULL DEFAULT 1,
  max_cajas INT UNSIGNED NOT NULL DEFAULT 1,
  configuracion_json LONGTEXT NULL,
  estado ENUM('activo','inactivo') NOT NULL DEFAULT 'activo',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_planes_codigo (codigo),
  KEY idx_planes_estado (estado)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS categorias_gastronomicas (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  codigo VARCHAR(60) NOT NULL,
  nombre VARCHAR(120) NOT NULL,
  configuracion_json LONGTEXT NOT NULL,
  estado ENUM('activo','inactivo') NOT NULL DEFAULT 'activo',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_categoria_codigo (codigo),
  KEY idx_categoria_estado (estado)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS negocios (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  plan_id BIGINT UNSIGNED NULL,
  categoria_gastronomica_id BIGINT UNSIGNED NOT NULL,
  nombre VARCHAR(180) NOT NULL,
  nombre_comercial VARCHAR(120) NULL,
  tipo_identificacion CHAR(2) NULL,
  identificacion VARCHAR(20) NULL,
  codigo_actividad VARCHAR(6) NULL,
  correo VARCHAR(160) NULL,
  telefono_codigo_pais VARCHAR(3) NOT NULL DEFAULT '506',
  telefono VARCHAR(20) NULL,
  moneda_base CHAR(3) NOT NULL DEFAULT 'CRC',
  usa_facturacion TINYINT(1) NOT NULL DEFAULT 0,
  estado ENUM('activo','suspendido','inactivo') NOT NULL DEFAULT 'activo',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_negocios_plan (plan_id),
  KEY idx_negocios_categoria (categoria_gastronomica_id),
  KEY idx_negocios_identificacion (tipo_identificacion, identificacion),
  KEY idx_negocios_estado (estado),
  CONSTRAINT fk_negocios_plan FOREIGN KEY (plan_id) REFERENCES planes(id),
  CONSTRAINT fk_negocios_categoria FOREIGN KEY (categoria_gastronomica_id) REFERENCES categorias_gastronomicas(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS sucursales (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  nombre VARCHAR(120) NOT NULL,
  codigo_interno VARCHAR(20) NOT NULL DEFAULT 'principal',
  codigo_fiscal CHAR(3) NOT NULL DEFAULT '001',
  provincia CHAR(1) NULL,
  canton CHAR(2) NULL,
  distrito CHAR(2) NULL,
  barrio VARCHAR(50) NULL,
  otras_sennas VARCHAR(250) NULL,
  correo VARCHAR(160) NULL,
  telefono_codigo_pais VARCHAR(3) NOT NULL DEFAULT '506',
  telefono VARCHAR(20) NULL,
  es_principal TINYINT(1) NOT NULL DEFAULT 0,
  estado ENUM('activa','inactiva','suspendida') NOT NULL DEFAULT 'activa',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_sucursal_codigo_fiscal (negocio_id, codigo_fiscal),
  KEY idx_sucursales_negocio_estado (negocio_id, estado),
  KEY idx_sucursales_ubicacion (provincia, canton, distrito),
  CONSTRAINT fk_sucursales_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS roles (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  codigo VARCHAR(60) NOT NULL,
  nombre VARCHAR(120) NOT NULL,
  alcance ENUM('plataforma','negocio','sucursal') NOT NULL DEFAULT 'negocio',
  estado ENUM('activo','inactivo') NOT NULL DEFAULT 'activo',
  PRIMARY KEY (id),
  UNIQUE KEY uq_roles_codigo (codigo)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS permisos (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  codigo VARCHAR(100) NOT NULL,
  nombre VARCHAR(140) NOT NULL,
  modulo VARCHAR(80) NOT NULL,
  PRIMARY KEY (id),
  UNIQUE KEY uq_permisos_codigo (codigo),
  KEY idx_permisos_modulo (modulo)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS rol_permisos (
  rol_id BIGINT UNSIGNED NOT NULL,
  permiso_id BIGINT UNSIGNED NOT NULL,
  PRIMARY KEY (rol_id, permiso_id),
  CONSTRAINT fk_rp_rol FOREIGN KEY (rol_id) REFERENCES roles(id),
  CONSTRAINT fk_rp_permiso FOREIGN KEY (permiso_id) REFERENCES permisos(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS usuarios (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NULL,
  sucursal_id BIGINT UNSIGNED NULL,
  rol_id BIGINT UNSIGNED NOT NULL,
  nombre VARCHAR(160) NOT NULL,
  correo VARCHAR(180) NOT NULL,
  password_hash VARCHAR(255) NOT NULL,
  estado ENUM('activo','suspendido','inactivo') NOT NULL DEFAULT 'activo',
  ultimo_acceso_at DATETIME NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_usuarios_correo (correo),
  KEY idx_usuarios_negocio_estado (negocio_id, estado),
  KEY idx_usuarios_sucursal (negocio_id, sucursal_id),
  KEY idx_usuarios_rol (rol_id),
  CONSTRAINT fk_usuarios_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_usuarios_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_usuarios_rol FOREIGN KEY (rol_id) REFERENCES roles(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


CREATE TABLE IF NOT EXISTS cajas (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  nombre VARCHAR(120) NOT NULL,
  codigo_terminal CHAR(5) NULL,
  licencia_codigo VARCHAR(80) NULL,
  emite_factura TINYINT(1) NOT NULL DEFAULT 0,
  estado ENUM('activa','inactiva','bloqueada') NOT NULL DEFAULT 'activa',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_cajas_sucursal_estado (negocio_id, sucursal_id, estado),
  KEY idx_cajas_terminal (negocio_id, sucursal_id, codigo_terminal),
  CONSTRAINT fk_cajas_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_cajas_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS caja_sesiones (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  caja_id BIGINT UNSIGNED NOT NULL,
  usuario_id BIGINT UNSIGNED NOT NULL,
  monto_inicial DECIMAL(18,5) NOT NULL DEFAULT 0,
  monto_efectivo_sistema DECIMAL(18,5) NOT NULL DEFAULT 0,
  monto_efectivo_contado DECIMAL(18,5) NOT NULL DEFAULT 0,
  diferencia_cierre DECIMAL(18,5) NOT NULL DEFAULT 0,
  total_ventas DECIMAL(18,5) NOT NULL DEFAULT 0,
  estado ENUM('abierta','cerrada','anulada') NOT NULL DEFAULT 'abierta',
  abierta_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  cerrada_at DATETIME NULL,
  observacion VARCHAR(255) NULL,
  PRIMARY KEY (id),
  KEY idx_caja_sesiones_abierta (negocio_id, sucursal_id, caja_id, estado),
  KEY idx_caja_sesiones_usuario (usuario_id, estado),
  CONSTRAINT fk_cs_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_cs_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_cs_caja FOREIGN KEY (caja_id) REFERENCES cajas(id),
  CONSTRAINT fk_cs_usuario FOREIGN KEY (usuario_id) REFERENCES usuarios(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS areas_restaurante (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  nombre VARCHAR(100) NOT NULL,
  orden SMALLINT UNSIGNED NOT NULL DEFAULT 1,
  estado ENUM('activa','inactiva') NOT NULL DEFAULT 'activa',
  PRIMARY KEY (id),
  KEY idx_areas_sucursal (negocio_id, sucursal_id, estado, orden),
  CONSTRAINT fk_areas_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_areas_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS mesas (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  area_id BIGINT UNSIGNED NOT NULL,
  nombre VARCHAR(40) NOT NULL,
  capacidad SMALLINT UNSIGNED NOT NULL DEFAULT 4,
  estado ENUM('LIBRE','OCUPADA','EN_COCINA','LISTA','EN_COBRO','RESERVADA','CERRADA','BLOQUEADA') NOT NULL DEFAULT 'LIBRE',
  orden SMALLINT UNSIGNED NOT NULL DEFAULT 1,
  PRIMARY KEY (id),
  KEY idx_mesas_mapa (negocio_id, sucursal_id, area_id, estado, orden),
  CONSTRAINT fk_mesas_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_mesas_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_mesas_area FOREIGN KEY (area_id) REFERENCES areas_restaurante(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS clientes (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NULL,
  nombre VARCHAR(160) NOT NULL,
  nombre_comercial VARCHAR(100) NULL,
  tipo_identificacion CHAR(2) NULL,
  identificacion VARCHAR(20) NULL,
  codigo_actividad VARCHAR(6) NULL,
  correo VARCHAR(160) NULL,
  telefono_codigo_pais VARCHAR(3) NOT NULL DEFAULT '506',
  telefono VARCHAR(20) NULL,
  provincia CHAR(1) NULL,
  canton CHAR(2) NULL,
  distrito CHAR(2) NULL,
  barrio VARCHAR(50) NULL,
  otras_sennas VARCHAR(160) NULL,
  estado ENUM('activo','inactivo') NOT NULL DEFAULT 'activo',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_clientes_negocio_nombre (negocio_id, nombre),
  KEY idx_clientes_identificacion (negocio_id, tipo_identificacion, identificacion),
  KEY idx_clientes_correo (negocio_id, correo),
  CONSTRAINT fk_clientes_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_clientes_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS productos_categorias (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NULL,
  nombre VARCHAR(120) NOT NULL,
  orden SMALLINT UNSIGNED NOT NULL DEFAULT 1,
  estado ENUM('activa','inactiva') NOT NULL DEFAULT 'activa',
  PRIMARY KEY (id),
  KEY idx_prod_cat_negocio (negocio_id, sucursal_id, estado, orden),
  CONSTRAINT fk_prod_cat_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_prod_cat_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS areas_produccion (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NULL,
  nombre VARCHAR(100) NOT NULL,
  impresora_nombre VARCHAR(120) NULL,
  estado ENUM('activa','inactiva') NOT NULL DEFAULT 'activa',
  PRIMARY KEY (id),
  KEY idx_area_prod_negocio (negocio_id, sucursal_id, estado),
  CONSTRAINT fk_area_prod_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_area_prod_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS productos (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NULL,
  categoria_id BIGINT UNSIGNED NULL,
  area_produccion_id BIGINT UNSIGNED NULL,
  tipo ENUM('producto_final','materia_prima','insumo_consumo','combo','servicio','reventa','preparado') NOT NULL DEFAULT 'producto_final',
  nombre VARCHAR(180) NOT NULL,
  codigo_interno VARCHAR(60) NULL,
  codigo_barras VARCHAR(80) NULL,
  codigo_cabys VARCHAR(13) NULL,
  unidad_medida VARCHAR(15) NOT NULL DEFAULT 'Unid',
  precio DECIMAL(18,5) NOT NULL DEFAULT 0,
  costo_promedio DECIMAL(18,5) NOT NULL DEFAULT 0,
  codigo_impuesto CHAR(2) NOT NULL DEFAULT '01',
  codigo_tarifa_iva CHAR(2) NULL DEFAULT '08',
  tarifa_iva DECIMAL(5,2) NOT NULL DEFAULT 13.00,
  permite_modificadores TINYINT(1) NOT NULL DEFAULT 0,
  permite_notas TINYINT(1) NOT NULL DEFAULT 1,
  afecta_inventario TINYINT(1) NOT NULL DEFAULT 1,
  imagen_path VARCHAR(255) NULL,
  estado ENUM('activo','inactivo') NOT NULL DEFAULT 'activo',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_productos_busqueda (negocio_id, sucursal_id, estado, nombre),
  KEY idx_productos_categoria (negocio_id, categoria_id, estado),
  KEY idx_productos_cabys (codigo_cabys),
  KEY idx_productos_codigo_barras (negocio_id, codigo_barras),
  CONSTRAINT fk_productos_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_productos_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_productos_categoria FOREIGN KEY (categoria_id) REFERENCES productos_categorias(id),
  CONSTRAINT fk_productos_area_prod FOREIGN KEY (area_produccion_id) REFERENCES areas_produccion(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS ventas (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  caja_id BIGINT UNSIGNED NULL,
  caja_sesion_id BIGINT UNSIGNED NULL,
  usuario_id BIGINT UNSIGNED NOT NULL,
  cliente_id BIGINT UNSIGNED NULL,
  origen ENUM('pos','mesa','barra','delivery','para_llevar','catalogo') NOT NULL DEFAULT 'pos',
  numero VARCHAR(40) NOT NULL,
  moneda CHAR(3) NOT NULL DEFAULT 'CRC',
  tipo_cambio DECIMAL(18,5) NOT NULL DEFAULT 1,
  subtotal DECIMAL(18,5) NOT NULL DEFAULT 0,
  descuento_total DECIMAL(18,5) NOT NULL DEFAULT 0,
  servicio_10 DECIMAL(18,5) NOT NULL DEFAULT 0,
  impuesto_total DECIMAL(18,5) NOT NULL DEFAULT 0,
  total DECIMAL(18,5) NOT NULL DEFAULT 0,
  estado ENUM('borrador','abierta','cobrada','facturada','anulada') NOT NULL DEFAULT 'borrador',
  idempotency_key VARCHAR(120) NULL,
  creada_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  cobrada_at DATETIME NULL,
  facturada_at DATETIME NULL,
  actualizada_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_ventas_numero (negocio_id, numero),
  UNIQUE KEY uq_ventas_idempotency (negocio_id, idempotency_key),
  KEY idx_ventas_negocio_fecha (negocio_id, creada_at),
  KEY idx_ventas_sucursal_fecha (negocio_id, sucursal_id, creada_at),
  KEY idx_ventas_estado (negocio_id, estado, creada_at),
  KEY idx_ventas_caja (negocio_id, sucursal_id, caja_id, creada_at),
  CONSTRAINT fk_ventas_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_ventas_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_ventas_caja FOREIGN KEY (caja_id) REFERENCES cajas(id),
  CONSTRAINT fk_ventas_sesion FOREIGN KEY (caja_sesion_id) REFERENCES caja_sesiones(id),
  CONSTRAINT fk_ventas_usuario FOREIGN KEY (usuario_id) REFERENCES usuarios(id),
  CONSTRAINT fk_ventas_cliente FOREIGN KEY (cliente_id) REFERENCES clientes(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS venta_lineas (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  venta_id BIGINT UNSIGNED NOT NULL,
  negocio_id BIGINT UNSIGNED NOT NULL,
  producto_id BIGINT UNSIGNED NOT NULL,
  numero_linea INT UNSIGNED NOT NULL,
  cantidad DECIMAL(18,3) NOT NULL,
  detalle VARCHAR(200) NOT NULL,
  precio_unitario DECIMAL(18,5) NOT NULL,
  descuento DECIMAL(18,5) NOT NULL DEFAULT 0,
  sub_total DECIMAL(18,5) NOT NULL,
  impuesto DECIMAL(18,5) NOT NULL DEFAULT 0,
  total_linea DECIMAL(18,5) NOT NULL,
  notas VARCHAR(255) NULL,
  modificadores_json LONGTEXT NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_venta_lineas_venta (venta_id),
  KEY idx_venta_lineas_producto (negocio_id, producto_id, creado_at),
  CONSTRAINT fk_vl_venta FOREIGN KEY (venta_id) REFERENCES ventas(id),
  CONSTRAINT fk_vl_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_vl_producto FOREIGN KEY (producto_id) REFERENCES productos(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS venta_pagos (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  venta_id BIGINT UNSIGNED NOT NULL,
  negocio_id BIGINT UNSIGNED NOT NULL,
  medio_pago CHAR(2) NOT NULL,
  medio_pago_otro VARCHAR(100) NULL,
  moneda CHAR(3) NOT NULL DEFAULT 'CRC',
  monto DECIMAL(18,5) NOT NULL,
  referencia VARCHAR(120) NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_venta_pagos_venta (venta_id),
  KEY idx_venta_pagos_medio (negocio_id, medio_pago, creado_at),
  CONSTRAINT fk_vp_venta FOREIGN KEY (venta_id) REFERENCES ventas(id),
  CONSTRAINT fk_vp_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS mesa_cuentas (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  mesa_id BIGINT UNSIGNED NOT NULL,
  mesero_id BIGINT UNSIGNED NULL,
  venta_id BIGINT UNSIGNED NULL,
  estado ENUM('abierta','en_cocina','lista','en_cobro','cerrada','anulada') NOT NULL DEFAULT 'abierta',
  comensales SMALLINT UNSIGNED NOT NULL DEFAULT 1,
  total_actual DECIMAL(18,5) NOT NULL DEFAULT 0,
  abierta_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  cerrada_at DATETIME NULL,
  PRIMARY KEY (id),
  KEY idx_mesa_cuentas_abiertas (negocio_id, sucursal_id, estado, mesa_id),
  KEY idx_mesa_cuentas_mesero (negocio_id, sucursal_id, mesero_id, estado),
  CONSTRAINT fk_mc_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_mc_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_mc_mesa FOREIGN KEY (mesa_id) REFERENCES mesas(id),
  CONSTRAINT fk_mc_mesero FOREIGN KEY (mesero_id) REFERENCES usuarios(id),
  CONSTRAINT fk_mc_venta FOREIGN KEY (venta_id) REFERENCES ventas(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS mesa_cuenta_lineas (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  cuenta_id BIGINT UNSIGNED NOT NULL,
  producto_id BIGINT UNSIGNED NOT NULL,
  cantidad DECIMAL(18,3) NOT NULL,
  precio_unitario DECIMAL(18,5) NOT NULL,
  impuesto DECIMAL(18,5) NOT NULL DEFAULT 0,
  total DECIMAL(18,5) NOT NULL,
  comensal_numero SMALLINT UNSIGNED NULL,
  estado_comanda ENUM('pendiente','enviada','preparando','lista','entregada','cancelada') NOT NULL DEFAULT 'pendiente',
  notas VARCHAR(255) NULL,
  modificadores_json LONGTEXT NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_mcl_cuenta (cuenta_id),
  KEY idx_mcl_producto (producto_id),
  KEY idx_mcl_estado_comanda (estado_comanda),
  CONSTRAINT fk_mcl_cuenta FOREIGN KEY (cuenta_id) REFERENCES mesa_cuentas(id),
  CONSTRAINT fk_mcl_producto FOREIGN KEY (producto_id) REFERENCES productos(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS comandas (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  cuenta_id BIGINT UNSIGNED NULL,
  venta_id BIGINT UNSIGNED NULL,
  area_produccion_id BIGINT UNSIGNED NOT NULL,
  estado ENUM('PENDIENTE','ENVIADA','PREPARANDO','LISTA','ENTREGADA','CANCELADA') NOT NULL DEFAULT 'PENDIENTE',
  enviada_at DATETIME NULL,
  lista_at DATETIME NULL,
  entregada_at DATETIME NULL,
  creada_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_comandas_estado (negocio_id, sucursal_id, estado, creada_at),
  KEY idx_comandas_area (negocio_id, sucursal_id, area_produccion_id, estado),
  CONSTRAINT fk_comandas_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_comandas_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_comandas_cuenta FOREIGN KEY (cuenta_id) REFERENCES mesa_cuentas(id),
  CONSTRAINT fk_comandas_venta FOREIGN KEY (venta_id) REFERENCES ventas(id),
  CONSTRAINT fk_comandas_area FOREIGN KEY (area_produccion_id) REFERENCES areas_produccion(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS comanda_lineas (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  comanda_id BIGINT UNSIGNED NOT NULL,
  producto_id BIGINT UNSIGNED NOT NULL,
  cantidad DECIMAL(18,3) NOT NULL,
  notas VARCHAR(255) NULL,
  modificadores_json LONGTEXT NULL,
  estado ENUM('PENDIENTE','PREPARANDO','LISTA','ENTREGADA','CANCELADA') NOT NULL DEFAULT 'PENDIENTE',
  PRIMARY KEY (id),
  KEY idx_cl_comanda (comanda_id),
  KEY idx_cl_producto (producto_id),
  CONSTRAINT fk_cl_comanda FOREIGN KEY (comanda_id) REFERENCES comandas(id),
  CONSTRAINT fk_cl_producto FOREIGN KEY (producto_id) REFERENCES productos(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS materias_primas (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  nombre VARCHAR(180) NOT NULL,
  unidad_base VARCHAR(15) NOT NULL,
  costo_promedio DECIMAL(18,5) NOT NULL DEFAULT 0,
  estado ENUM('activo','inactivo') NOT NULL DEFAULT 'activo',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_materias_negocio (negocio_id, estado, nombre),
  CONSTRAINT fk_mp_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS recetas (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  producto_id BIGINT UNSIGNED NOT NULL,
  nombre VARCHAR(180) NOT NULL,
  rendimiento DECIMAL(18,5) NOT NULL DEFAULT 1,
  estado ENUM('activa','inactiva') NOT NULL DEFAULT 'activa',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_receta_producto (negocio_id, producto_id),
  CONSTRAINT fk_recetas_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_recetas_producto FOREIGN KEY (producto_id) REFERENCES productos(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS receta_detalles (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  receta_id BIGINT UNSIGNED NOT NULL,
  materia_prima_id BIGINT UNSIGNED NOT NULL,
  cantidad DECIMAL(18,5) NOT NULL,
  unidad_base VARCHAR(15) NOT NULL,
  merma_porcentaje DECIMAL(8,5) NOT NULL DEFAULT 0,
  afecta_inventario TINYINT(1) NOT NULL DEFAULT 1,
  PRIMARY KEY (id),
  KEY idx_rd_receta (receta_id),
  KEY idx_rd_materia (materia_prima_id),
  CONSTRAINT fk_rd_receta FOREIGN KEY (receta_id) REFERENCES recetas(id),
  CONSTRAINT fk_rd_materia FOREIGN KEY (materia_prima_id) REFERENCES materias_primas(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS inventario (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  materia_prima_id BIGINT UNSIGNED NOT NULL,
  stock_actual DECIMAL(18,5) NOT NULL DEFAULT 0,
  stock_minimo DECIMAL(18,5) NOT NULL DEFAULT 0,
  costo_promedio DECIMAL(18,5) NOT NULL DEFAULT 0,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_inventario_insumo_sucursal (negocio_id, sucursal_id, materia_prima_id),
  KEY idx_inventario_stock (negocio_id, sucursal_id, stock_actual),
  CONSTRAINT fk_inv_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_inv_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_inv_materia FOREIGN KEY (materia_prima_id) REFERENCES materias_primas(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS kardex (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  materia_prima_id BIGINT UNSIGNED NOT NULL,
  tipo_movimiento ENUM('COMPRA','VENTA','COMANDA_CONSUMO_PENDIENTE','VENTA_CONFIRMADA','AJUSTE_POSITIVO','AJUSTE_NEGATIVO','MERMA','TRASLADO_SALIDA','TRASLADO_ENTRADA','PRODUCCION','REVERSA') NOT NULL,
  cantidad DECIMAL(18,5) NOT NULL,
  costo DECIMAL(18,5) NOT NULL DEFAULT 0,
  referencia_tipo VARCHAR(60) NULL,
  referencia_id BIGINT UNSIGNED NULL,
  usuario_id BIGINT UNSIGNED NULL,
  motivo VARCHAR(255) NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_kardex_item_fecha (negocio_id, sucursal_id, materia_prima_id, creado_at),
  KEY idx_kardex_referencia (referencia_tipo, referencia_id),
  CONSTRAINT fk_kardex_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_kardex_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_kardex_materia FOREIGN KEY (materia_prima_id) REFERENCES materias_primas(id),
  CONSTRAINT fk_kardex_usuario FOREIGN KEY (usuario_id) REFERENCES usuarios(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS auditoria (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NULL,
  sucursal_id BIGINT UNSIGNED NULL,
  usuario_id BIGINT UNSIGNED NULL,
  accion VARCHAR(120) NOT NULL,
  modulo VARCHAR(120) NULL,
  referencia_tipo VARCHAR(80) NULL,
  referencia_id BIGINT UNSIGNED NULL,
  detalle LONGTEXT NULL,
  ip VARCHAR(45) NULL,
  user_agent VARCHAR(255) NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_auditoria_negocio_fecha (negocio_id, creado_at),
  KEY idx_auditoria_referencia (referencia_tipo, referencia_id),
  KEY idx_auditoria_usuario (usuario_id, creado_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS seguridad_eventos (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NULL,
  usuario_id BIGINT UNSIGNED NULL,
  tipo VARCHAR(80) NOT NULL,
  severidad ENUM('baja','media','alta','critica') NOT NULL DEFAULT 'media',
  ip_hash CHAR(64) NULL,
  detalle LONGTEXT NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_seguridad_tipo_fecha (tipo, creado_at),
  KEY idx_seguridad_ip (ip_hash, creado_at),
  KEY idx_seguridad_negocio (negocio_id, creado_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS rate_limits (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  ip_hash CHAR(64) NOT NULL,
  accion VARCHAR(80) NOT NULL,
  window_start DATETIME NOT NULL,
  attempts INT UNSIGNED NOT NULL DEFAULT 1,
  blocked_until DATETIME NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_rate_window (ip_hash, accion, window_start),
  KEY idx_rate_blocked (blocked_until)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
SET NAMES utf8mb4;
SET time_zone = '-06:00';

CREATE TABLE IF NOT EXISTS terminales_fiscales (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  caja_id BIGINT UNSIGNED NOT NULL,
  cod_sucursal CHAR(3) NOT NULL,
  cod_terminal CHAR(5) NOT NULL,
  ambiente ENUM('sandbox','production') NOT NULL DEFAULT 'sandbox',
  estado ENUM('activa','inactiva','suspendida') NOT NULL DEFAULT 'activa',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_terminal_fiscal (negocio_id, cod_sucursal, cod_terminal, ambiente),
  KEY idx_tf_caja (negocio_id, sucursal_id, caja_id, estado),
  CONSTRAINT fk_tf_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_tf_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_tf_caja FOREIGN KEY (caja_id) REFERENCES cajas(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS api_keys (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  caja_id BIGINT UNSIGNED NOT NULL,
  terminal_fiscal_id BIGINT UNSIGNED NULL,
  key_hash CHAR(64) NOT NULL,
  key_prefix VARCHAR(16) NOT NULL,
  permisos_json LONGTEXT NULL,
  rate_limit_minuto INT UNSIGNED NOT NULL DEFAULT 120,
  ultimo_uso_at DATETIME NULL,
  estado ENUM('activa','suspendida','revocada') NOT NULL DEFAULT 'activa',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_api_key_hash (key_hash),
  KEY idx_api_keys_terminal (terminal_fiscal_id, estado),
  KEY idx_api_keys_contexto (negocio_id, sucursal_id, caja_id, estado),
  CONSTRAINT fk_ak_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_ak_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_ak_caja FOREIGN KEY (caja_id) REFERENCES cajas(id),
  CONSTRAINT fk_ak_tf FOREIGN KEY (terminal_fiscal_id) REFERENCES terminales_fiscales(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS mh_credenciales (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  ambiente ENUM('sandbox','production') NOT NULL DEFAULT 'sandbox',
  mh_username VARCHAR(120) NOT NULL,
  mh_password_cipher TEXT NOT NULL,
  cert_path VARCHAR(255) NOT NULL,
  cert_pin_cipher TEXT NOT NULL,
  cert_vigente_hasta DATETIME NULL,
  estado ENUM('activa','inactiva','vencida') NOT NULL DEFAULT 'activa',
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_mh_cred_negocio_ambiente (negocio_id, ambiente),
  CONSTRAINT fk_mh_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS consecutivos_fiscales (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  terminal_fiscal_id BIGINT UNSIGNED NOT NULL,
  cod_sucursal CHAR(3) NOT NULL,
  cod_terminal CHAR(5) NOT NULL,
  tipo_documento CHAR(2) NOT NULL,
  ambiente ENUM('sandbox','production') NOT NULL DEFAULT 'sandbox',
  ultimo_numero BIGINT UNSIGNED NOT NULL DEFAULT 0,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_consecutivo_fiscal (negocio_id, cod_sucursal, cod_terminal, tipo_documento, ambiente),
  KEY idx_consecutivo_terminal (terminal_fiscal_id, tipo_documento),
  CONSTRAINT fk_cf_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_cf_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_cf_tf FOREIGN KEY (terminal_fiscal_id) REFERENCES terminales_fiscales(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS documentos_electronicos (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  caja_id BIGINT UNSIGNED NULL,
  terminal_fiscal_id BIGINT UNSIGNED NULL,
  venta_id BIGINT UNSIGNED NULL,
  usuario_id BIGINT UNSIGNED NULL,
  tipo_documento CHAR(2) NOT NULL,
  xml_schema_version VARCHAR(10) NOT NULL DEFAULT '4.4',
  ambiente ENUM('sandbox','production') NOT NULL DEFAULT 'sandbox',
  clave CHAR(50) NULL,
  consecutivo CHAR(20) NULL,
  proveedor_sistemas VARCHAR(20) NULL,
  situacion CHAR(2) NOT NULL DEFAULT '1',
  fecha_emision VARCHAR(35) NULL,
  condicion_venta CHAR(2) NOT NULL DEFAULT '01',
  condicion_venta_otros VARCHAR(100) NULL,
  plazo_credito INT UNSIGNED NULL,
  moneda CHAR(3) NOT NULL DEFAULT 'CRC',
  tipo_cambio DECIMAL(18,5) NOT NULL DEFAULT 1,
  receptor_nombre VARCHAR(100) NULL,
  receptor_nombre_comercial VARCHAR(80) NULL,
  receptor_tipo_identificacion CHAR(2) NULL,
  receptor_identificacion VARCHAR(20) NULL,
  receptor_codigo_actividad VARCHAR(6) NULL,
  receptor_correo VARCHAR(160) NULL,
  receptor_provincia CHAR(1) NULL,
  receptor_canton CHAR(2) NULL,
  receptor_distrito CHAR(2) NULL,
  receptor_barrio VARCHAR(50) NULL,
  receptor_otras_sennas VARCHAR(160) NULL,
  total_serv_gravados DECIMAL(18,5) NOT NULL DEFAULT 0,
  total_serv_exentos DECIMAL(18,5) NOT NULL DEFAULT 0,
  total_serv_exonerados DECIMAL(18,5) NOT NULL DEFAULT 0,
  total_serv_no_sujetos DECIMAL(18,5) NOT NULL DEFAULT 0,
  total_merc_gravadas DECIMAL(18,5) NOT NULL DEFAULT 0,
  total_merc_exentas DECIMAL(18,5) NOT NULL DEFAULT 0,
  total_merc_exoneradas DECIMAL(18,5) NOT NULL DEFAULT 0,
  total_merc_no_sujetas DECIMAL(18,5) NOT NULL DEFAULT 0,
  total_gravado DECIMAL(18,5) NOT NULL DEFAULT 0,
  total_exento DECIMAL(18,5) NOT NULL DEFAULT 0,
  total_exonerado DECIMAL(18,5) NOT NULL DEFAULT 0,
  total_no_sujeto DECIMAL(18,5) NOT NULL DEFAULT 0,
  total_venta DECIMAL(18,5) NOT NULL DEFAULT 0,
  total_descuentos DECIMAL(18,5) NOT NULL DEFAULT 0,
  total_venta_neta DECIMAL(18,5) NOT NULL DEFAULT 0,
  total_impuesto DECIMAL(18,5) NOT NULL DEFAULT 0,
  total_imp_asum_emi DECIMAL(18,5) NOT NULL DEFAULT 0,
  total_iva_devuelto DECIMAL(18,5) NOT NULL DEFAULT 0,
  servicio_10 DECIMAL(18,5) NOT NULL DEFAULT 0,
  total_comprobante DECIMAL(18,5) NOT NULL DEFAULT 0,
  total_desglose_impuestos_json LONGTEXT NULL,
  idempotency_key VARCHAR(120) NULL,
  estado ENUM('BORRADOR','GENERADO','FIRMADO','ENVIADO','ACEPTADO','RECHAZADO','PENDIENTE','ERROR','ANULADO_POR_NC') NOT NULL DEFAULT 'BORRADOR',
  respuesta_hacienda VARCHAR(30) NULL,
  respuesta_error_hacienda TEXT NULL,
  xml_firmado_path VARCHAR(255) NULL,
  xml_respuesta_path VARCHAR(255) NULL,
  pdf_path VARCHAR(255) NULL,
  xml_firmado LONGTEXT NULL,
  xml_respuesta LONGTEXT NULL,
  webhook_url VARCHAR(500) NULL,
  webhook_token VARCHAR(180) NULL,
  correo_enviado_at DATETIME NULL,
  correo_error VARCHAR(255) NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_documento_clave (clave),
  UNIQUE KEY uq_documento_consecutivo (negocio_id, sucursal_id, caja_id, tipo_documento, consecutivo),
  UNIQUE KEY uq_documento_idempotency (negocio_id, idempotency_key),
  KEY idx_documentos_estado (negocio_id, estado, creado_at),
  KEY idx_documentos_venta (venta_id),
  KEY idx_documentos_fecha (negocio_id, sucursal_id, creado_at),
  KEY idx_documentos_receptor (negocio_id, receptor_identificacion),
  CONSTRAINT fk_de_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_de_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_de_caja FOREIGN KEY (caja_id) REFERENCES cajas(id),
  CONSTRAINT fk_de_tf FOREIGN KEY (terminal_fiscal_id) REFERENCES terminales_fiscales(id),
  CONSTRAINT fk_de_venta FOREIGN KEY (venta_id) REFERENCES ventas(id),
  CONSTRAINT fk_de_usuario FOREIGN KEY (usuario_id) REFERENCES usuarios(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS documentos_detalle (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  documento_id BIGINT UNSIGNED NOT NULL,
  numero_linea INT UNSIGNED NOT NULL,
  producto_id BIGINT UNSIGNED NULL,
  codigo_cabys VARCHAR(13) NOT NULL,
  codigo_comercial_tipo CHAR(2) NULL,
  codigo_comercial VARCHAR(20) NULL,
  unidad_medida VARCHAR(15) NOT NULL,
  unidad_medida_comercial VARCHAR(20) NULL,
  partida_arancelaria VARCHAR(12) NULL,
  tipo_transaccion CHAR(2) NULL,
  detalle VARCHAR(200) NOT NULL,
  registro_medicamento VARCHAR(100) NULL,
  forma_farmaceutica VARCHAR(3) NULL,
  numero_vin_serie VARCHAR(17) NULL,
  cantidad DECIMAL(18,3) NOT NULL,
  precio_unitario DECIMAL(18,5) NOT NULL,
  monto_total DECIMAL(18,5) NOT NULL,
  sub_total DECIMAL(18,5) NOT NULL,
  base_imponible DECIMAL(18,5) NOT NULL DEFAULT 0,
  monto_total_linea DECIMAL(18,5) NOT NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_doc_detalle_documento (documento_id),
  KEY idx_doc_detalle_cabys (codigo_cabys),
  CONSTRAINT fk_dd_documento FOREIGN KEY (documento_id) REFERENCES documentos_electronicos(id),
  CONSTRAINT fk_dd_producto FOREIGN KEY (producto_id) REFERENCES productos(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS documentos_detalle_descuentos (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  documento_detalle_id BIGINT UNSIGNED NOT NULL,
  codigo_descuento CHAR(2) NOT NULL,
  codigo_descuento_otros VARCHAR(100) NULL,
  naturaleza_descuento VARCHAR(80) NULL,
  monto_descuento DECIMAL(18,5) NOT NULL DEFAULT 0,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_doc_desc_detalle (documento_detalle_id),
  CONSTRAINT fk_ddd_detalle FOREIGN KEY (documento_detalle_id) REFERENCES documentos_detalle(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS documentos_detalle_impuestos (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  documento_detalle_id BIGINT UNSIGNED NOT NULL,
  codigo CHAR(2) NOT NULL,
  codigo_otros VARCHAR(100) NULL,
  codigo_tarifa_iva CHAR(2) NULL,
  tarifa DECIMAL(5,2) NULL,
  factor_calculo_iva DECIMAL(10,5) NULL,
  monto DECIMAL(18,5) NOT NULL DEFAULT 0,
  monto_exoneracion DECIMAL(18,5) NOT NULL DEFAULT 0,
  impuesto_asumido_emisor_fabrica DECIMAL(18,5) NOT NULL DEFAULT 0,
  impuesto_neto DECIMAL(18,5) NOT NULL DEFAULT 0,
  exoneracion_tipo_documento_ex VARCHAR(4) NULL,
  exoneracion_tipo_documento_ex_otros VARCHAR(100) NULL,
  exoneracion_numero_documento VARCHAR(40) NULL,
  exoneracion_articulo VARCHAR(6) NULL,
  exoneracion_inciso VARCHAR(6) NULL,
  exoneracion_nombre_institucion VARCHAR(4) NULL,
  exoneracion_nombre_institucion_otros VARCHAR(160) NULL,
  exoneracion_fecha_emision VARCHAR(35) NULL,
  exoneracion_tarifa DECIMAL(8,5) NOT NULL DEFAULT 0,
  exoneracion_json LONGTEXT NULL,
  datos_especificos_json LONGTEXT NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_doc_imp_detalle (documento_detalle_id),
  KEY idx_doc_imp_codigo (codigo, codigo_tarifa_iva),
  CONSTRAINT fk_ddi_detalle FOREIGN KEY (documento_detalle_id) REFERENCES documentos_detalle(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS documentos_medios_pago (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  documento_id BIGINT UNSIGNED NOT NULL,
  tipo_medio_pago CHAR(2) NOT NULL,
  medio_pago_otro VARCHAR(100) NULL,
  total_medio_pago DECIMAL(18,5) NULL,
  orden SMALLINT UNSIGNED NOT NULL DEFAULT 1,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_dmp_documento (documento_id),
  KEY idx_dmp_tipo (tipo_medio_pago),
  CONSTRAINT fk_dmp_documento FOREIGN KEY (documento_id) REFERENCES documentos_electronicos(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS documentos_referencias (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  documento_id BIGINT UNSIGNED NOT NULL,
  tipo_doc_ir CHAR(2) NOT NULL,
  tipo_doc_ref_otro VARCHAR(100) NULL,
  numero VARCHAR(50) NOT NULL,
  fecha_emision_ir VARCHAR(35) NOT NULL,
  codigo CHAR(2) NOT NULL,
  codigo_referencia_otro VARCHAR(100) NULL,
  razon VARCHAR(180) NOT NULL,
  orden SMALLINT UNSIGNED NOT NULL DEFAULT 1,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_doc_ref_documento (documento_id),
  KEY idx_doc_ref_numero (numero),
  CONSTRAINT fk_dr_documento FOREIGN KEY (documento_id) REFERENCES documentos_electronicos(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS documentos_xml (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  documento_id BIGINT UNSIGNED NOT NULL,
  tipo ENUM('generado','firmado','respuesta','mensaje_receptor') NOT NULL,
  path VARCHAR(255) NULL,
  contenido LONGTEXT NULL,
  hash_sha256 CHAR(64) NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_doc_xml_documento (documento_id, tipo),
  KEY idx_doc_xml_hash (hash_sha256),
  CONSTRAINT fk_dx_documento FOREIGN KEY (documento_id) REFERENCES documentos_electronicos(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS mensajes_receptor (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  terminal_fiscal_id BIGINT UNSIGNED NULL,
  tipo_documento CHAR(2) NOT NULL DEFAULT '05',
  clave CHAR(50) NOT NULL,
  numero_consecutivo_receptor CHAR(20) NOT NULL,
  fecha_emision_doc VARCHAR(35) NOT NULL,
  mensaje CHAR(1) NOT NULL,
  detalle_mensaje VARCHAR(160) NULL,
  numero_cedula_emisor VARCHAR(20) NOT NULL,
  tipo_identificacion_emisor CHAR(2) NOT NULL,
  numero_cedula_receptor VARCHAR(20) NOT NULL,
  tipo_identificacion_receptor CHAR(2) NOT NULL,
  monto_total_impuesto DECIMAL(18,5) NULL,
  total_factura DECIMAL(18,5) NOT NULL,
  codigo_actividad VARCHAR(6) NULL,
  condicion_impuesto CHAR(2) NULL,
  monto_total_impuesto_acreditar DECIMAL(18,5) NULL,
  monto_total_de_gasto_aplicable DECIMAL(18,5) NULL,
  estado ENUM('BORRADOR','FIRMADO','ENVIADO','ACEPTADO','RECHAZADO','ERROR') NOT NULL DEFAULT 'BORRADOR',
  xml_firmado LONGTEXT NULL,
  xml_respuesta LONGTEXT NULL,
  respuesta_hacienda VARCHAR(30) NULL,
  respuesta_error_hacienda TEXT NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_mr_clave_consecutivo (clave, numero_consecutivo_receptor),
  KEY idx_mr_negocio_fecha (negocio_id, creado_at),
  KEY idx_mr_estado (negocio_id, estado, creado_at),
  CONSTRAINT fk_mr_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_mr_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_mr_tf FOREIGN KEY (terminal_fiscal_id) REFERENCES terminales_fiscales(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS tipo_cambio_cache (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  moneda CHAR(3) NOT NULL DEFAULT 'USD',
  fecha DATE NOT NULL,
  compra DECIMAL(18,5) NULL,
  venta DECIMAL(18,5) NULL,
  fuente VARCHAR(60) NOT NULL DEFAULT 'hacienda',
  raw_response LONGTEXT NULL,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_tc_moneda_fecha (moneda, fecha)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT IGNORE INTO planes (codigo, nombre, max_sucursales, max_cajas, configuracion_json) VALUES
('base_restaurante', 'Plan Base Restaurante', 1, 1, '{"incluye_pos":true,"incluye_mesas":true,"incluye_comandas":true}'),
('crecimiento', 'Plan Crecimiento', 3, 5, '{"incluye_pos":true,"incluye_mesas":true,"incluye_comandas":true,"incluye_inventario":true}');

INSERT IGNORE INTO categorias_gastronomicas (codigo, nombre, configuracion_json) VALUES
('pollo_frito', 'Pollo frito', '{"modo_pos":"rapido","usa_mesas":false,"usa_comandas":true,"usa_recetas":true,"usa_combos":true,"usa_modificadores":true,"usa_delivery":true,"usa_servicio_10":false,"usa_prefactura":false,"usa_impresoras_area":true,"inventario_modo":"receta_materia_prima"}'),
('hamburgueseria', 'Hamburguesería', '{"modo_pos":"rapido","usa_mesas":false,"usa_comandas":true,"usa_recetas":true,"usa_combos":true,"usa_modificadores":true,"usa_delivery":true,"usa_servicio_10":false,"usa_prefactura":false,"usa_impresoras_area":true,"inventario_modo":"receta_materia_prima"}'),
('pizzeria', 'Pizzería', '{"modo_pos":"rapido","usa_mesas":true,"usa_comandas":true,"usa_recetas":true,"usa_combos":true,"usa_modificadores":true,"usa_delivery":true,"usa_servicio_10":false,"usa_prefactura":true,"usa_impresoras_area":true,"inventario_modo":"receta_materia_prima"}'),
('cafeteria', 'Cafetería', '{"modo_pos":"rapido","usa_mesas":true,"usa_comandas":true,"usa_recetas":true,"usa_combos":true,"usa_modificadores":true,"usa_delivery":true,"usa_servicio_10":false,"usa_prefactura":true,"usa_impresoras_area":true,"inventario_modo":"receta_materia_prima"}'),
('bar', 'Bar', '{"modo_pos":"barra","usa_mesas":true,"usa_comandas":true,"usa_recetas":true,"usa_combos":true,"usa_modificadores":true,"usa_delivery":false,"usa_servicio_10":true,"usa_prefactura":true,"usa_impresoras_area":true,"inventario_modo":"receta_materia_prima"}'),
('restaurante_mesa', 'Restaurante con mesas', '{"modo_pos":"mesas","usa_mesas":true,"usa_comandas":true,"usa_recetas":true,"usa_combos":true,"usa_modificadores":true,"usa_delivery":true,"usa_servicio_10":true,"usa_prefactura":true,"usa_division_cuenta":true,"usa_impresoras_area":true,"inventario_modo":"receta_materia_prima"}'),
('comida_rapida_general', 'Comida rápida general', '{"modo_pos":"rapido","usa_mesas":false,"usa_comandas":true,"usa_recetas":true,"usa_combos":true,"usa_modificadores":true,"usa_delivery":true,"usa_servicio_10":false,"usa_prefactura":false,"usa_impresoras_area":true,"inventario_modo":"receta_materia_prima"}'),
('dark_kitchen', 'Dark kitchen', '{"modo_pos":"delivery","usa_mesas":false,"usa_comandas":true,"usa_recetas":true,"usa_combos":true,"usa_modificadores":true,"usa_delivery":true,"usa_servicio_10":false,"usa_prefactura":false,"usa_impresoras_area":true,"inventario_modo":"receta_materia_prima"}');

INSERT IGNORE INTO roles (codigo, nombre, alcance) VALUES
('super_admin', 'Super Admin', 'plataforma'),
('dueno', 'Dueño del negocio', 'negocio'),
('admin', 'Administrador', 'negocio'),
('admin_sucursal', 'Administrador de sucursal', 'sucursal'),
('cajero', 'Cajero', 'sucursal'),
('mesero', 'Mesero', 'sucursal'),
('cocina', 'Cocina', 'sucursal'),
('barra', 'Barra', 'sucursal'),
('inventario', 'Inventario', 'sucursal'),
('contador', 'Contador', 'negocio'),
('soporte', 'Soporte', 'plataforma');

INSERT IGNORE INTO permisos (codigo, nombre, modulo) VALUES
('ventas.ver','Ver ventas','ventas'),
('ventas.crear','Crear ventas','ventas'),
('ventas.cobrar','Cobrar ventas','ventas'),
('ventas.anular','Anular ventas','ventas'),
('mesas.abrir','Abrir mesas','mesas'),
('mesas.cambiar','Cambiar mesas','mesas'),
('mesas.unificar','Unificar mesas','mesas'),
('comandas.ver','Ver comandas','comandas'),
('comandas.preparar','Preparar comandas','comandas'),
('comandas.cancelar','Cancelar comandas','comandas'),
('inventario.ver','Ver inventario','inventario'),
('inventario.ajustar','Ajustar inventario','inventario'),
('recetas.editar','Editar recetas','recetas'),
('compras.crear','Crear compras','compras'),
('facturacion.emitir','Emitir facturación','facturacion'),
('facturacion.anular','Anular facturación','facturacion'),
('caja.abrir','Abrir caja','caja'),
('caja.cerrar','Cerrar caja','caja'),
('reportes.ver','Ver reportes','reportes'),
('configuracion.editar','Editar configuración','configuracion');
SET NAMES utf8mb4;
SET time_zone = '-06:00';

CREATE TABLE IF NOT EXISTS public_leads (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  nombre VARCHAR(160) NOT NULL,
  telefono VARCHAR(40) NOT NULL,
  correo VARCHAR(180) NULL,
  negocio VARCHAR(160) NULL,
  mensaje TEXT NULL,
  origen VARCHAR(80) NOT NULL DEFAULT 'landing',
  estado ENUM('nuevo','revision','contactado','demo_agendada','cerrado','descartado') NOT NULL DEFAULT 'nuevo',
  ip VARCHAR(60) NULL,
  user_agent VARCHAR(255) NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_public_leads_estado_fecha (estado, creado_at),
  KEY idx_public_leads_correo (correo),
  KEY idx_public_leads_telefono (telefono)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS panel_sesiones_api (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  usuario_id BIGINT UNSIGNED NOT NULL,
  negocio_id BIGINT UNSIGNED NULL,
  sucursal_id BIGINT UNSIGNED NULL,
  token_hash CHAR(64) NOT NULL,
  device_name VARCHAR(80) NULL,
  ip VARCHAR(60) NULL,
  user_agent VARCHAR(255) NULL,
  expires_at DATETIME NOT NULL,
  revoked_at DATETIME NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_panel_token_hash (token_hash),
  KEY idx_panel_sesion_usuario (usuario_id, expires_at),
  KEY idx_panel_sesion_negocio (negocio_id, sucursal_id, expires_at),
  CONSTRAINT fk_panel_sesion_usuario FOREIGN KEY (usuario_id) REFERENCES usuarios(id),
  CONSTRAINT fk_panel_sesion_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_panel_sesion_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS planes_sucursales (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  plan_id BIGINT UNSIGNED NOT NULL,
  estado ENUM('activo','suspendido','cancelado') NOT NULL DEFAULT 'activo',
  inicia_at DATETIME NULL,
  vence_at DATETIME NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_plan_sucursal_negocio (negocio_id, estado),
  KEY idx_plan_sucursal_sucursal (sucursal_id, estado),
  CONSTRAINT fk_ps_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_ps_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_ps_plan FOREIGN KEY (plan_id) REFERENCES planes(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS modulos (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  codigo VARCHAR(80) NOT NULL,
  nombre VARCHAR(140) NOT NULL,
  descripcion VARCHAR(255) NULL,
  estado ENUM('activo','inactivo') NOT NULL DEFAULT 'activo',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_modulos_codigo (codigo),
  KEY idx_modulos_estado (estado)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS modulos_negocio (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  modulo_id BIGINT UNSIGNED NOT NULL,
  activo TINYINT(1) NOT NULL DEFAULT 1,
  origen ENUM('plan','categoria','addon','manual') NOT NULL DEFAULT 'plan',
  configuracion_json LONGTEXT NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_modulo_negocio (negocio_id, modulo_id),
  KEY idx_modulos_negocio_activo (negocio_id, activo),
  CONSTRAINT fk_mn_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_mn_modulo FOREIGN KEY (modulo_id) REFERENCES modulos(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS productos_modificadores (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  producto_id BIGINT UNSIGNED NOT NULL,
  nombre VARCHAR(120) NOT NULL,
  tipo ENUM('agregar','quitar','cambiar','nota') NOT NULL DEFAULT 'agregar',
  precio_adicional DECIMAL(18,5) NOT NULL DEFAULT 0,
  materia_prima_id BIGINT UNSIGNED NULL,
  cantidad_consumo DECIMAL(18,5) NOT NULL DEFAULT 0,
  afecta_inventario TINYINT(1) NOT NULL DEFAULT 0,
  estado ENUM('activo','inactivo') NOT NULL DEFAULT 'activo',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_pm_producto (negocio_id, producto_id, estado),
  KEY idx_pm_materia (materia_prima_id),
  CONSTRAINT fk_pm_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_pm_producto FOREIGN KEY (producto_id) REFERENCES productos(id),
  CONSTRAINT fk_pm_materia FOREIGN KEY (materia_prima_id) REFERENCES materias_primas(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS combos (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  producto_id BIGINT UNSIGNED NOT NULL,
  nombre VARCHAR(160) NOT NULL,
  permite_cambio_componentes TINYINT(1) NOT NULL DEFAULT 1,
  estado ENUM('activo','inactivo') NOT NULL DEFAULT 'activo',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_combo_producto (producto_id),
  KEY idx_combos_negocio (negocio_id, estado),
  CONSTRAINT fk_combos_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_combos_producto FOREIGN KEY (producto_id) REFERENCES productos(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS combo_detalles (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  combo_id BIGINT UNSIGNED NOT NULL,
  producto_id BIGINT UNSIGNED NOT NULL,
  grupo VARCHAR(80) NULL,
  cantidad DECIMAL(18,3) NOT NULL DEFAULT 1,
  obligatorio TINYINT(1) NOT NULL DEFAULT 1,
  precio_adicional DECIMAL(18,5) NOT NULL DEFAULT 0,
  orden SMALLINT UNSIGNED NOT NULL DEFAULT 1,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_combo_detalles_combo (combo_id, grupo, orden),
  KEY idx_combo_detalles_producto (producto_id),
  CONSTRAINT fk_cd_combo FOREIGN KEY (combo_id) REFERENCES combos(id),
  CONSTRAINT fk_cd_producto FOREIGN KEY (producto_id) REFERENCES productos(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS insumos_consumo (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  materia_prima_id BIGINT UNSIGNED NOT NULL,
  nombre VARCHAR(160) NOT NULL,
  unidad_base VARCHAR(20) NOT NULL,
  estado ENUM('activo','inactivo') NOT NULL DEFAULT 'activo',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_insumos_negocio (negocio_id, estado),
  CONSTRAINT fk_ic_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_ic_materia FOREIGN KEY (materia_prima_id) REFERENCES materias_primas(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS inventario_movimientos (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  materia_prima_id BIGINT UNSIGNED NOT NULL,
  tipo_movimiento ENUM('COMPRA','VENTA','COMANDA_CONSUMO_PENDIENTE','VENTA_CONFIRMADA','AJUSTE_POSITIVO','AJUSTE_NEGATIVO','MERMA','TRASLADO_SALIDA','TRASLADO_ENTRADA','PRODUCCION','REVERSA') NOT NULL,
  cantidad DECIMAL(18,5) NOT NULL,
  unidad_base VARCHAR(20) NOT NULL,
  costo DECIMAL(18,5) NOT NULL DEFAULT 0,
  referencia_tipo VARCHAR(50) NULL,
  referencia_id BIGINT UNSIGNED NULL,
  usuario_id BIGINT UNSIGNED NULL,
  motivo VARCHAR(255) NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_inv_mov_item_fecha (negocio_id, sucursal_id, materia_prima_id, creado_at),
  KEY idx_inv_mov_ref (referencia_tipo, referencia_id),
  CONSTRAINT fk_im_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_im_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_im_materia FOREIGN KEY (materia_prima_id) REFERENCES materias_primas(id),
  CONSTRAINT fk_im_usuario FOREIGN KEY (usuario_id) REFERENCES usuarios(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS proveedores (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  nombre VARCHAR(180) NOT NULL,
  tipo_identificacion CHAR(2) NULL,
  identificacion VARCHAR(20) NULL,
  correo VARCHAR(160) NULL,
  telefono VARCHAR(40) NULL,
  direccion VARCHAR(255) NULL,
  codigo_actividad VARCHAR(6) NULL,
  condicion_pago ENUM('contado','credito') NOT NULL DEFAULT 'contado',
  plazo_credito INT UNSIGNED NULL,
  estado ENUM('activo','inactivo') NOT NULL DEFAULT 'activo',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_proveedores_negocio (negocio_id, estado),
  KEY idx_proveedores_identificacion (tipo_identificacion, identificacion),
  CONSTRAINT fk_proveedores_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS ordenes_compra (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  proveedor_id BIGINT UNSIGNED NOT NULL,
  numero VARCHAR(40) NOT NULL,
  estado ENUM('borrador','enviada','aprobada','recibida_parcial','recibida','cancelada') NOT NULL DEFAULT 'borrador',
  moneda CHAR(3) NOT NULL DEFAULT 'CRC',
  subtotal DECIMAL(18,5) NOT NULL DEFAULT 0,
  impuesto DECIMAL(18,5) NOT NULL DEFAULT 0,
  total DECIMAL(18,5) NOT NULL DEFAULT 0,
  creado_por BIGINT UNSIGNED NULL,
  aprobado_por BIGINT UNSIGNED NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_oc_numero (negocio_id, numero),
  KEY idx_oc_estado (negocio_id, sucursal_id, estado, creado_at),
  CONSTRAINT fk_oc_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_oc_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_oc_proveedor FOREIGN KEY (proveedor_id) REFERENCES proveedores(id),
  CONSTRAINT fk_oc_creado_por FOREIGN KEY (creado_por) REFERENCES usuarios(id),
  CONSTRAINT fk_oc_aprobado_por FOREIGN KEY (aprobado_por) REFERENCES usuarios(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS orden_compra_lineas (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  orden_compra_id BIGINT UNSIGNED NOT NULL,
  materia_prima_id BIGINT UNSIGNED NULL,
  producto_id BIGINT UNSIGNED NULL,
  descripcion VARCHAR(200) NOT NULL,
  cantidad DECIMAL(18,5) NOT NULL,
  unidad_compra VARCHAR(30) NOT NULL,
  factor_unidad_base DECIMAL(18,8) NOT NULL DEFAULT 1,
  costo_unitario DECIMAL(18,5) NOT NULL DEFAULT 0,
  impuesto DECIMAL(18,5) NOT NULL DEFAULT 0,
  total_linea DECIMAL(18,5) NOT NULL DEFAULT 0,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_oc_lineas_oc (orden_compra_id),
  CONSTRAINT fk_ocl_oc FOREIGN KEY (orden_compra_id) REFERENCES ordenes_compra(id),
  CONSTRAINT fk_ocl_materia FOREIGN KEY (materia_prima_id) REFERENCES materias_primas(id),
  CONSTRAINT fk_ocl_producto FOREIGN KEY (producto_id) REFERENCES productos(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS compras (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  proveedor_id BIGINT UNSIGNED NOT NULL,
  orden_compra_id BIGINT UNSIGNED NULL,
  clave VARCHAR(50) NULL,
  consecutivo VARCHAR(20) NULL,
  fecha_emision VARCHAR(35) NULL,
  condicion_compra ENUM('contado','credito') NOT NULL DEFAULT 'contado',
  moneda CHAR(3) NOT NULL DEFAULT 'CRC',
  subtotal DECIMAL(18,5) NOT NULL DEFAULT 0,
  impuesto DECIMAL(18,5) NOT NULL DEFAULT 0,
  total DECIMAL(18,5) NOT NULL DEFAULT 0,
  xml_path VARCHAR(255) NULL,
  xml_original LONGTEXT NULL,
  estado ENUM('borrador','validada','recibida','anulada') NOT NULL DEFAULT 'borrador',
  creado_por BIGINT UNSIGNED NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_compras_clave (clave),
  KEY idx_compras_estado (negocio_id, sucursal_id, estado, creado_at),
  CONSTRAINT fk_compras_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_compras_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_compras_proveedor FOREIGN KEY (proveedor_id) REFERENCES proveedores(id),
  CONSTRAINT fk_compras_oc FOREIGN KEY (orden_compra_id) REFERENCES ordenes_compra(id),
  CONSTRAINT fk_compras_usuario FOREIGN KEY (creado_por) REFERENCES usuarios(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS compra_lineas (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  compra_id BIGINT UNSIGNED NOT NULL,
  materia_prima_id BIGINT UNSIGNED NULL,
  producto_id BIGINT UNSIGNED NULL,
  detalle VARCHAR(200) NOT NULL,
  cantidad DECIMAL(18,5) NOT NULL,
  unidad_compra VARCHAR(30) NOT NULL,
  factor_unidad_base DECIMAL(18,8) NOT NULL DEFAULT 1,
  cantidad_unidad_base DECIMAL(18,5) NOT NULL DEFAULT 0,
  costo_unitario DECIMAL(18,5) NOT NULL DEFAULT 0,
  impuesto DECIMAL(18,5) NOT NULL DEFAULT 0,
  total_linea DECIMAL(18,5) NOT NULL DEFAULT 0,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_compra_lineas_compra (compra_id),
  CONSTRAINT fk_cl_compra FOREIGN KEY (compra_id) REFERENCES compras(id),
  CONSTRAINT fk_cl_materia FOREIGN KEY (materia_prima_id) REFERENCES materias_primas(id),
  CONSTRAINT fk_cl_producto FOREIGN KEY (producto_id) REFERENCES productos(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS cuentas_cobrar (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  cliente_id BIGINT UNSIGNED NOT NULL,
  venta_id BIGINT UNSIGNED NULL,
  documento_id BIGINT UNSIGNED NULL,
  numero VARCHAR(40) NOT NULL,
  moneda CHAR(3) NOT NULL DEFAULT 'CRC',
  total DECIMAL(18,5) NOT NULL DEFAULT 0,
  saldo DECIMAL(18,5) NOT NULL DEFAULT 0,
  vence_at DATE NULL,
  estado ENUM('pendiente','abonada','pagada','vencida','anulada') NOT NULL DEFAULT 'pendiente',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_cxc_numero (negocio_id, numero),
  KEY idx_cxc_cliente_estado (negocio_id, cliente_id, estado),
  CONSTRAINT fk_cxc_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_cxc_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_cxc_cliente FOREIGN KEY (cliente_id) REFERENCES clientes(id),
  CONSTRAINT fk_cxc_venta FOREIGN KEY (venta_id) REFERENCES ventas(id),
  CONSTRAINT fk_cxc_doc FOREIGN KEY (documento_id) REFERENCES documentos_electronicos(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS cuentas_cobrar_movimientos (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  cuenta_cobrar_id BIGINT UNSIGNED NOT NULL,
  usuario_id BIGINT UNSIGNED NULL,
  tipo ENUM('cargo','abono','ajuste','anulacion') NOT NULL,
  monto DECIMAL(18,5) NOT NULL,
  medio_pago VARCHAR(30) NULL,
  referencia VARCHAR(120) NULL,
  observacion VARCHAR(255) NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_cxc_mov_cuenta (cuenta_cobrar_id, creado_at),
  CONSTRAINT fk_cxcm_cuenta FOREIGN KEY (cuenta_cobrar_id) REFERENCES cuentas_cobrar(id),
  CONSTRAINT fk_cxcm_usuario FOREIGN KEY (usuario_id) REFERENCES usuarios(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS cuentas_pagar (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  proveedor_id BIGINT UNSIGNED NOT NULL,
  compra_id BIGINT UNSIGNED NULL,
  numero VARCHAR(40) NOT NULL,
  moneda CHAR(3) NOT NULL DEFAULT 'CRC',
  total DECIMAL(18,5) NOT NULL DEFAULT 0,
  saldo DECIMAL(18,5) NOT NULL DEFAULT 0,
  vence_at DATE NULL,
  estado ENUM('pendiente','abonada','pagada','vencida','anulada') NOT NULL DEFAULT 'pendiente',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_cxp_numero (negocio_id, numero),
  KEY idx_cxp_proveedor_estado (negocio_id, proveedor_id, estado),
  CONSTRAINT fk_cxp_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_cxp_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_cxp_proveedor FOREIGN KEY (proveedor_id) REFERENCES proveedores(id),
  CONSTRAINT fk_cxp_compra FOREIGN KEY (compra_id) REFERENCES compras(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS cuentas_pagar_movimientos (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  cuenta_pagar_id BIGINT UNSIGNED NOT NULL,
  usuario_id BIGINT UNSIGNED NULL,
  tipo ENUM('cargo','abono','ajuste','anulacion') NOT NULL,
  monto DECIMAL(18,5) NOT NULL,
  medio_pago VARCHAR(30) NULL,
  referencia VARCHAR(120) NULL,
  observacion VARCHAR(255) NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_cxp_mov_cuenta (cuenta_pagar_id, creado_at),
  CONSTRAINT fk_cxpm_cuenta FOREIGN KEY (cuenta_pagar_id) REFERENCES cuentas_pagar(id),
  CONSTRAINT fk_cxpm_usuario FOREIGN KEY (usuario_id) REFERENCES usuarios(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS cierres_caja (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  caja_id BIGINT UNSIGNED NOT NULL,
  caja_sesion_id BIGINT UNSIGNED NOT NULL,
  usuario_id BIGINT UNSIGNED NOT NULL,
  monto_esperado DECIMAL(18,5) NOT NULL DEFAULT 0,
  monto_contado DECIMAL(18,5) NOT NULL DEFAULT 0,
  diferencia DECIMAL(18,5) NOT NULL DEFAULT 0,
  resumen_json LONGTEXT NULL,
  pdf_path VARCHAR(255) NULL,
  enviado_correo_at DATETIME NULL,
  estado ENUM('generado','enviado','anulado') NOT NULL DEFAULT 'generado',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_cierre_sesion (caja_sesion_id),
  KEY idx_cierres_fecha (negocio_id, sucursal_id, creado_at),
  CONSTRAINT fk_cierre_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_cierre_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_cierre_caja FOREIGN KEY (caja_id) REFERENCES cajas(id),
  CONSTRAINT fk_cierre_sesion FOREIGN KEY (caja_sesion_id) REFERENCES caja_sesiones(id),
  CONSTRAINT fk_cierre_usuario FOREIGN KEY (usuario_id) REFERENCES usuarios(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS prefacturas (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  mesa_cuenta_id BIGINT UNSIGNED NULL,
  venta_id BIGINT UNSIGNED NULL,
  numero VARCHAR(40) NOT NULL,
  subtotal DECIMAL(18,5) NOT NULL DEFAULT 0,
  servicio_10 DECIMAL(18,5) NOT NULL DEFAULT 0,
  impuesto DECIMAL(18,5) NOT NULL DEFAULT 0,
  total DECIMAL(18,5) NOT NULL DEFAULT 0,
  detalle_json LONGTEXT NULL,
  impresa_at DATETIME NULL,
  creado_por BIGINT UNSIGNED NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_prefactura_numero (negocio_id, numero),
  KEY idx_prefacturas_cuenta (mesa_cuenta_id),
  CONSTRAINT fk_pref_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_pref_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_pref_cuenta FOREIGN KEY (mesa_cuenta_id) REFERENCES mesa_cuentas(id),
  CONSTRAINT fk_pref_venta FOREIGN KEY (venta_id) REFERENCES ventas(id),
  CONSTRAINT fk_pref_usuario FOREIGN KEY (creado_por) REFERENCES usuarios(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS impresoras (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  nombre VARCHAR(120) NOT NULL,
  tipo ENUM('caja','cocina','barra','postres','otro') NOT NULL DEFAULT 'otro',
  driver VARCHAR(80) NULL,
  ruta VARCHAR(255) NULL,
  estado ENUM('activa','inactiva') NOT NULL DEFAULT 'activa',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_impresoras_sucursal (negocio_id, sucursal_id, estado),
  CONSTRAINT fk_imp_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_imp_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS producto_impresoras_area (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  producto_categoria_id BIGINT UNSIGNED NULL,
  producto_id BIGINT UNSIGNED NULL,
  area_produccion_id BIGINT UNSIGNED NULL,
  impresora_id BIGINT UNSIGNED NOT NULL,
  estado ENUM('activo','inactivo') NOT NULL DEFAULT 'activo',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_pia_producto (negocio_id, producto_id, estado),
  KEY idx_pia_categoria (negocio_id, producto_categoria_id, estado),
  CONSTRAINT fk_pia_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_pia_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_pia_categoria FOREIGN KEY (producto_categoria_id) REFERENCES productos_categorias(id),
  CONSTRAINT fk_pia_producto FOREIGN KEY (producto_id) REFERENCES productos(id),
  CONSTRAINT fk_pia_area FOREIGN KEY (area_produccion_id) REFERENCES areas_produccion(id),
  CONSTRAINT fk_pia_impresora FOREIGN KEY (impresora_id) REFERENCES impresoras(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS servicio_10_config (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  aplica_en_mesas TINYINT(1) NOT NULL DEFAULT 1,
  aplica_en_para_llevar TINYINT(1) NOT NULL DEFAULT 0,
  aplica_en_delivery TINYINT(1) NOT NULL DEFAULT 0,
  mostrar_separado TINYINT(1) NOT NULL DEFAULT 1,
  porcentaje DECIMAL(5,2) NOT NULL DEFAULT 10.00,
  estado ENUM('activo','inactivo') NOT NULL DEFAULT 'activo',
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_servicio10_negocio (negocio_id),
  CONSTRAINT fk_s10_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT IGNORE INTO modulos (codigo, nombre, descripcion) VALUES
('pos', 'POS', 'Venta rápida y cobro'),
('mesas', 'Mesas', 'Áreas, mesas, comensales y prefactura'),
('comandas', 'Comandas', 'Órdenes internas para cocina y barra'),
('inventario_recetas', 'Inventario por recetas', 'Consumo de materia prima por venta'),
('compras_xml', 'Compras XML', 'Carga de XML, costos y cuentas por pagar'),
('facturacion_electronica', 'Facturación electrónica', 'FE, TE, NC, ND, FEC y mensajes receptor'),
('cuentas_cobrar', 'Cuentas por cobrar', 'Crédito y abonos de clientes'),
('cuentas_pagar', 'Cuentas por pagar', 'Crédito y pagos a proveedores'),
('reportes', 'Reportes', 'Cierres, impuestos y rendimiento'),
('integradores', 'Integradores', 'Contratos API e integraciones externas');
