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');
