-- =====================================================
-- sp_TarjetaConsultarDetalleLote.sql - STORED PROCEDURE PARA DETALLE DE LOTES
-- =====================================================

USE [Sis2000]
GO


IF OBJECT_ID('sp_TarjetaConsultarDetalleLote', 'P') IS NOT NULL 
    DROP PROCEDURE sp_TarjetaConsultarDetalleLote;
GO


CREATE PROCEDURE sp_TarjetaConsultarDetalleLote
    @p_ctarlot INT
AS
BEGIN
    SET NOCOUNT ON;
    
    SELECT 
        L.ctarlot,
        L.xnombre_lote,
        L.ccanalalt,
        L.cplan,
        L.cramos,
        L.fingreso,
        L.cusuario,
        C.xcanalalt,
        -- Producto: ya no existe en tatarlot, mostrar valor por defecto
        'No especificado' AS xproducto,
        -- Plan desde maplanes usando cplan y cramos de tatarlot
        PLANES.xplan AS xplan,
        -- Datos del cliente API Tarjeta
        API.cci_rif,  -- ID Cliente
        CL.xcliente,  -- Nombre del cliente
        CL.itipopers,
        (SELECT TOP 1 LOWER(LTRIM(RTRIM(xcorreo))) FROM maclient_correo WHERE cci_rif = API.cci_rif) AS xemail,
        (SELECT COUNT(*) FROM tatarjeta WHERE ctarlot = L.ctarlot) AS ctarjetas,
        API.cproductor AS cproductor_sisip,
        (SELECT TOP 1 LTRIM(RTRIM(xproductor)) FROM maproduc WHERE cproductor = API.cproductor) AS xproductor_sisip,
        -- Estatus temporal (necesitamos saber de dónde viene el estatus real)
        'Activo' AS cestado  -- Placeholder hasta saber la columna real
    FROM tatarlot L
    LEFT JOIN macanalalt C ON C.ccanalalt = L.ccanalalt
    LEFT JOIN maplanes PLANES ON PLANES.cplan = L.cplan AND PLANES.cramo = L.cramos
    LEFT JOIN maclient_api API ON API.ccanalalt = L.ccanalalt
    LEFT JOIN maclient CL ON CL.cci_rif = API.cci_rif
    WHERE L.ctarlot = @p_ctarlot;
END
GO

PRINT 'SP sp_TarjetaConsultarDetalleLote creado exitosamente'
GO
