-- Cotizaciones internas separadas de facturacion fiscal

INSERT IGNORE INTO tipo_operacion (id, codigo, descripcion, estado, created_at) VALUES
(3, 'COTIZACION', 'Cotizacion', 1, NOW());

INSERT IGNORE INTO modulos (id, codigo, nombre, categoria, estado, created_at) VALUES
(18, 'cotizaciones', 'Cotizaciones', 'CORE', 1, NOW());

SET @cotizaciones_table_exists := (
    SELECT COUNT(*)
    FROM information_schema.tables
    WHERE table_schema = DATABASE()
      AND table_name = 'facturacion_cotizaciones'
);

SET @sql_cotizaciones := IF(
    @cotizaciones_table_exists = 0,
    'CREATE TABLE facturacion_cotizaciones (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        empresa_id BIGINT UNSIGNED NOT NULL,
        tercero_id BIGINT UNSIGNED NULL,
        tipo_operacion_id TINYINT UNSIGNED NOT NULL DEFAULT 3 COMMENT ''3=Cotizacion'',
        serie VARCHAR(20) NOT NULL DEFAULT ''COT'',
        numero INT UNSIGNED NOT NULL DEFAULT 1,
        fecha_emision DATE NOT NULL,
        fecha_vigencia DATE NULL,
        dias_vigencia INT UNSIGNED NOT NULL DEFAULT 15,
        moneda CHAR(3) NOT NULL DEFAULT ''PEN'',
        subtotal DECIMAL(15,2) NOT NULL DEFAULT 0.00,
        igv DECIMAL(15,2) NOT NULL DEFAULT 0.00,
        total DECIMAL(15,2) NOT NULL DEFAULT 0.00,
        estado TINYINT UNSIGNED NOT NULL DEFAULT 2 COMMENT ''1=Borrador, 2=Emitida, 5=Anulada'',
        observacion TEXT NULL,
        created_by BIGINT UNSIGNED NULL,
        updated_by BIGINT UNSIGNED NULL,
        created_at DATETIME NOT NULL,
        updated_at DATETIME NULL,
        deleted_at DATETIME NULL,
        UNIQUE KEY uq_cotizacion_empresa_serie_numero (empresa_id, serie, numero),
        KEY idx_cotizacion_empresa_fecha (empresa_id, fecha_emision),
        KEY idx_cotizacion_tercero (tercero_id),
        KEY idx_cotizacion_tipo_operacion (tipo_operacion_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci',
    'SELECT 1'
);
PREPARE stmt_cotizaciones FROM @sql_cotizaciones;
EXECUTE stmt_cotizaciones;
DEALLOCATE PREPARE stmt_cotizaciones;

SET @cotizaciones_detalles_exists := (
    SELECT COUNT(*)
    FROM information_schema.tables
    WHERE table_schema = DATABASE()
      AND table_name = 'facturacion_cotizacion_detalles'
);

SET @sql_cotizaciones_detalles := IF(
    @cotizaciones_detalles_exists = 0,
    'CREATE TABLE facturacion_cotizacion_detalles (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        cotizacion_id BIGINT UNSIGNED NOT NULL,
        catalogo_item_id BIGINT UNSIGNED NULL,
        unidad_medida_id BIGINT UNSIGNED NULL,
        item VARCHAR(30) NULL,
        descripcion VARCHAR(255) NOT NULL,
        cantidad DECIMAL(15,4) NOT NULL DEFAULT 0.0000,
        unidad_medida VARCHAR(20) NOT NULL,
        valor_unitario DECIMAL(15,2) NOT NULL DEFAULT 0.00,
        precio_unitario DECIMAL(15,2) NOT NULL DEFAULT 0.00,
        descuento DECIMAL(15,2) NOT NULL DEFAULT 0.00,
        afecto_igv TINYINT(1) NOT NULL DEFAULT 1,
        afectacion_igv_id BIGINT UNSIGNED NULL,
        subtotal DECIMAL(15,2) NOT NULL DEFAULT 0.00,
        igv DECIMAL(15,2) NOT NULL DEFAULT 0.00,
        total DECIMAL(15,2) NOT NULL DEFAULT 0.00,
        created_at DATETIME NOT NULL,
        updated_at DATETIME NULL,
        deleted_at DATETIME NULL,
        KEY idx_cot_det_cotizacion (cotizacion_id),
        KEY idx_cot_det_item (catalogo_item_id),
        KEY idx_cot_det_unidad (unidad_medida_id),
        CONSTRAINT fk_cot_det_cotizacion FOREIGN KEY (cotizacion_id) REFERENCES facturacion_cotizaciones(id),
        CONSTRAINT fk_cot_det_item FOREIGN KEY (catalogo_item_id) REFERENCES catalogo_items(id),
        CONSTRAINT fk_cot_det_unidad FOREIGN KEY (unidad_medida_id) REFERENCES unidades_medida(id),
        CONSTRAINT fk_cot_det_afectacion FOREIGN KEY (afectacion_igv_id) REFERENCES catalogo_afectaciones_igv(id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci',
    'SELECT 1'
);
PREPARE stmt_cotizaciones_detalles FROM @sql_cotizaciones_detalles;
EXECUTE stmt_cotizaciones_detalles;
DEALLOCATE PREPARE stmt_cotizaciones_detalles;

INSERT IGNORE INTO empresa_modulos (empresa_id, modulo_id, habilitado, created_at)
SELECT e.id, m.id, 1, NOW()
FROM empresas e
INNER JOIN modulos m
WHERE e.deleted_at IS NULL
  AND m.codigo IN ('cotizaciones');
