-- ============================================================
--  Migración 2026-10-13_01 · Solicitud de cotización con varias ofertas
-- ------------------------------------------------------------
--  cotizacion_venta pasa a ser solo la SOLICITUD del cliente (proyecto,
--  lo que pide, archivos). Su número cambia de CV- a SV-.
--  cotizacion_venta_oferta: cada propuesta que arma el cotizador sobre
--    una solicitud, con su propio número de cotización (CV-AAAA-NNNN),
--    materiales, margen y totales. Ventas imprime cada una y elige una
--    (seleccionada); las demás quedan descartadas.
--  cotizacion_venta_material: ahora cuelga de la oferta (id_oferta).
--  cotizacion_venta_historial: bitácora de la solicitud (cambios que
--    pide el cliente, envíos, ofertas, selección).
--  cotizacion_venta.total / costo_total: los de la oferta seleccionada
--    o, si aún no hay, los de la última oferta lista (los usa el perfil
--    del cliente).
--  Datos existentes: cada cotización con materiales pasa a ser una
--  oferta que conserva el número CV- original.
-- ============================================================
USE tinsa_db;

CREATE TABLE `cotizacion_venta_oferta` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `id_cotizacion_venta` int(10) unsigned NOT NULL,
  `numero` varchar(50) NOT NULL,
  `nombre` varchar(150) DEFAULT NULL,
  `nota` text DEFAULT NULL,
  `estado` enum('borrador','lista','seleccionada','descartada') NOT NULL DEFAULT 'borrador',
  `margen_global` decimal(5,2) DEFAULT NULL,
  `subtotal` decimal(12,2) NOT NULL DEFAULT 0.00,
  `total` decimal(12,2) NOT NULL DEFAULT 0.00,
  `costo_total` decimal(12,2) NOT NULL DEFAULT 0.00,
  `id_usuario_creo` int(10) unsigned DEFAULT NULL,
  `fecha_lista` datetime DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_cvo_numero` (`numero`),
  KEY `idx_cvo_cotizacion` (`id_cotizacion_venta`),
  KEY `fk_cvo_usuario` (`id_usuario_creo`),
  CONSTRAINT `fk_cvo_cotizacion` FOREIGN KEY (`id_cotizacion_venta`) REFERENCES `cotizacion_venta` (`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_cvo_usuario` FOREIGN KEY (`id_usuario_creo`) REFERENCES `usuarios` (`id_usuario`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `chk_cvo_margen_global` CHECK (`margen_global` is null or `margen_global` >= 0 and `margen_global` < 100)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

CREATE TABLE `cotizacion_venta_historial` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `id_cotizacion_venta` int(10) unsigned NOT NULL,
  `tipo` varchar(40) NOT NULL,
  `descripcion` varchar(255) NOT NULL,
  `cambios` text DEFAULT NULL,
  `id_usuario` int(10) unsigned DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  KEY `idx_cvh_cotizacion` (`id_cotizacion_venta`),
  KEY `fk_cvh_usuario` (`id_usuario`),
  CONSTRAINT `fk_cvh_cotizacion` FOREIGN KEY (`id_cotizacion_venta`) REFERENCES `cotizacion_venta` (`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_cvh_usuario` FOREIGN KEY (`id_usuario`) REFERENCES `usuarios` (`id_usuario`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

-- Cada cotización que ya tenía materiales pasa a ser una oferta con su número CV-
INSERT INTO cotizacion_venta_oferta
       (id_cotizacion_venta, numero, estado, margen_global, subtotal, total, costo_total, id_usuario_creo, fecha_lista, created_at)
SELECT cv.id, cv.numero,
       CASE cv.estado
         WHEN 'aprobada' THEN 'seleccionada'
         WHEN 'presupuestada' THEN 'lista'
         WHEN 'enviada' THEN 'lista'
         WHEN 'rechazada' THEN 'descartada'
         WHEN 'cancelada' THEN 'descartada'
         ELSE 'borrador'
       END,
       cv.margen_global, cv.subtotal, cv.total, cv.costo_total, cv.id_usuario_cotizador,
       CASE WHEN cv.estado IN ('presupuestada','enviada','aprobada') THEN cv.updated_at END,
       cv.created_at
  FROM cotizacion_venta cv
 WHERE EXISTS (SELECT 1 FROM cotizacion_venta_material m WHERE m.id_cotizacion_venta = cv.id);

-- Los materiales cuelgan ahora de la oferta
ALTER TABLE `cotizacion_venta_material`
  ADD COLUMN `id_oferta` int(10) unsigned DEFAULT NULL AFTER `id`;

UPDATE cotizacion_venta_material m
  JOIN cotizacion_venta_oferta o ON o.id_cotizacion_venta = m.id_cotizacion_venta
   SET m.id_oferta = o.id;

ALTER TABLE `cotizacion_venta_material`
  DROP FOREIGN KEY `fk_cvm_cotizacion`,
  DROP KEY `idx_cvm_cotizacion`,
  DROP COLUMN `id_cotizacion_venta`,
  MODIFY `id_oferta` int(10) unsigned NOT NULL,
  ADD KEY `idx_cvm_oferta` (`id_oferta`),
  ADD CONSTRAINT `fk_cvm_oferta` FOREIGN KEY (`id_oferta`) REFERENCES `cotizacion_venta_oferta` (`id`) ON DELETE CASCADE;

-- La solicitud toma su propio correlativo: SV-AAAA-NNNN
UPDATE cotizacion_venta SET numero = CONCAT('SV-', SUBSTRING(numero, 4)) WHERE numero LIKE 'CV-%';

INSERT INTO cotizacion_venta_historial (id_cotizacion_venta, tipo, descripcion, id_usuario, created_at)
SELECT id, 'creada', 'Solicitud registrada', id_usuario_vendedor, created_at FROM cotizacion_venta;
