Create PROC [dbo].[SupplyChainHIX_UnsendInvoice]
    @InvoiceType TINYINT,
    @InputStartDate VARCHAR(10),
    @InputEndDate VARCHAR(10)
AS

DECLARE @StartDate DATE = CAST(dbo.ShamsiToMiladi(@InputStartDate) AS DATE),
        @EndDate DATE = CAST(dbo.ShamsiToMiladi(@InputEndDate) AS DATE);

--DECLARE @dt TABLE
--(
--    InvoiceId BIGINT,
--    DetailGoodsCount INT,
--    CustomerCode VARCHAR(5),
--    CustomerName VARCHAR(5),
--    HIXCode VARCHAR(MAX)
--);

--INSERT INTO @dt
--(
--    InvoiceId,
--    DetailGoodsCount,
--    CustomerCode,
--    CustomerName,
--    HIXCode
--)
--SELECT dt.Id_Havaleh InvoiceId,
--       COUNT(dt.Id_Havaleh) DetailGoodsCount,
--       ci.Guy_Code,
--       dt.Reciver,
--       ci.HIXCode
--FROM Havaleh dt
--    JOIN dbo.headH hd
--        ON hd.Id_Havaleh = dt.Id_Havaleh
--    JOIN dbo.Guy cu
--        ON cu.Guy_Code = dt.Reciver
--    LEFT JOIN dbo.tblGuy_Info ci
--        ON cu.Guy_Code = cu.Guy_Code
--WHERE hd.Tarikh_faktor
--      BETWEEN @StartDate AND @EndDate
--      AND Kind_Flag IN ( 7, 5, 9 )
--GROUP BY dt.Id_Havaleh,
--         ci.Guy_Code,
--         dt.Reciver,
--         ci.HIXCode;

--SELECT dt.Id_Havaleh InvoiceId,
--       COUNT(dt.Id_Havaleh) DetailGoodsCount
--FROM Havaleh dt
--GROUP BY dt.Id_Havaleh;

SELECT hd.Id_Havaleh InvoiceId,
       hd.Nu_Forosh FactorNumber,
       hd.Recive_Name CustomerName,
       hd.Tot_Price_forosh TotalInvoicePrice,
       hd.Note,
       dbo.MiladiToShamsi(hd.Tarikh_faktor) InvoiceDate,
       dt.DetailGoodsCount,
       InvoiceType = CASE
                         WHEN hd.Kind_Flag = 5 THEN
                             'فروش'
                         WHEN hd.Kind_Flag = 7 THEN
                             'خرده'
                         WHEN hd.Kind_Flag = '9' THEN
                             'عمده'
                     END,
       cu.HIXCode
FROM dbo.headH hd
    JOIN
    (
        SELECT dt.Id_Havaleh InvoiceId,
               COUNT(dt.Id_Havaleh) DetailGoodsCount
        FROM Havaleh dt
        GROUP BY dt.Id_Havaleh
    ) AS dt
        ON dt.InvoiceId = hd.Id_Havaleh
    LEFT JOIN dbo.tblGuy_Info cu
        ON cu.Guy_Code = dt.InvoiceId
WHERE Kind_Flag IN ( 7, 5, 9 )
      AND hd.Id_Havaleh NOT IN (
                                   SELECT InvoiceId FROM dbo.SupplyChainHIXInvoice GROUP BY InvoiceId
                               )
      AND hd.Kind_Flag = CASE
                             WHEN @InvoiceType = 1 THEN
                                 7
                             WHEN @InvoiceType = 2 THEN
                                 5
                             WHEN @InvoiceType = 3 THEN
                                 9
                             ELSE
                                 hd.Kind_Flag
                         END
      AND CAST(hd.Tarikh_faktor AS DATE)
      BETWEEN @StartDate AND @EndDate
ORDER BY hd.Tarikh_faktor;