-- ============================================================
--  Migración 2026-10-14_05 · Al cliente se le cotiza el ÍTEM
-- ------------------------------------------------------------
--  Los materiales de un ítem son su costo interno; lo que se cotiza al
--  cliente es el ítem en sí. El margen se aplica al costo total del ítem:
--    precio del ítem = costo del ítem / (1 - margen / 100)
--  cotizacion_venta_oferta_item: costo_total, margen (NULL = sin definir), precio.
--  cotizacion_venta_material: queda solo con costos; precio_unitario,
--    margen y subtotal_venta dejan de usarse (quedan en 0 / NULL).
--  Datos existentes: el precio de cada ítem es la suma de lo que ya
--  valían sus líneas y su margen el que resulta de precio vs. costo
--  (NULL si a alguna línea le faltaba margen).
-- ============================================================
USE tinsa_db;

ALTER TABLE `cotizacion_venta_oferta_item`
  ADD COLUMN `costo_total` decimal(12,2) NOT NULL DEFAULT 0.00 AFTER `paquete_parametros`,
  ADD COLUMN `margen` decimal(6,2) DEFAULT NULL AFTER `costo_total`,
  ADD COLUMN `precio` decimal(12,2) NOT NULL DEFAULT 0.00 AFTER `margen`;

UPDATE cotizacion_venta_oferta_item i
  JOIN (SELECT id_item,
               SUM(subtotal_costo) AS costo,
               SUM(subtotal_venta) AS venta,
               SUM(margen IS NULL AND precio_unitario <= 0) AS sin_margen,
               MIN(margen) AS m_min, MAX(margen) AS m_max
          FROM cotizacion_venta_material GROUP BY id_item) t ON t.id_item = i.id
   SET i.costo_total = t.costo,
       i.precio      = IF(t.sin_margen > 0, 0, t.venta),
       i.margen      = CASE
                         WHEN t.sin_margen > 0 THEN NULL
                         WHEN t.m_min IS NOT NULL AND t.m_min = t.m_max THEN t.m_min
                         WHEN t.venta > 0 THEN ROUND((t.venta - t.costo) * 100 / t.venta, 2)
                         ELSE 0
                       END;

UPDATE cotizacion_venta_material SET precio_unitario = 0, margen = NULL, subtotal_venta = 0;

UPDATE cotizacion_venta_oferta o
   SET o.costo_total = (SELECT COALESCE(SUM(i.costo_total), 0) FROM cotizacion_venta_oferta_item i WHERE i.id_oferta = o.id),
       o.total       = (SELECT COALESCE(SUM(i.precio), 0)      FROM cotizacion_venta_oferta_item i WHERE i.id_oferta = o.id),
       o.subtotal    = (SELECT COALESCE(SUM(i.precio), 0)      FROM cotizacion_venta_oferta_item i WHERE i.id_oferta = o.id);
