CREATE PROCEDURE dbo.BalanceEconomyExtGet @AHotelCustomerNumber INT, @AType INT AS
SET NOCOUNT ON

/*
  Created by Kent Johansen, november 2012
  Changes:
  
*/

CREATE TABLE #tab
(
  FolioNumber INT,
  AllAmount MONEY,
  DepositAmount MONEY,
  InhouseAmount MONEY
)

INSERT INTO #tab EXEC BalanceEconomyExt @AHotelCustomerNumber

IF @AType = 0
BEGIN
  -- list of inhouse debtors
  SELECT #tab.FolioNumber, 
  CASE WHEN (ISNULL(#tab.AllAmount, 0) - ISNULL(#tab.DepositAmount, 0) <> 0) THEN 
    (ISNULL(#tab.AllAmount, 0) - ISNULL(#tab.DepositAmount, 0))
  ELSE 
    #tab.InhouseAmount END AS DebtorAmount, 
  ReservationAddress.LastName + CASE WHEN ReservationAddress.FirstName = '' THEN '' ELSE ', ' + ReservationAddress.FirstName END AS FullName
  FROM #tab
  INNER JOIN Folios WITH (NOLOCK) ON Folios.FolioNumber = #tab.FolioNumber
  LEFT OUTER JOIN ReservationAddress WITH (NOLOCK) ON ReservationAddress.AddressNumber = Folios.ReservationAddressNumber
  WHERE (ISNULL(#tab.AllAmount, 0) - ISNULL(#tab.DepositAmount, 0) <> 0) OR (ISNULL(#tab.InhouseAmount, 0) <> 0)
END
ELSE IF @AType = 1
BEGIN
  -- List of folios with diff
  SELECT #tab.FolioNumber, #tab.AllAmount-#tab.DepositAmount AS DebtorAmount, #tab.InhouseAmount,
  ReservationAddress.LastName + CASE WHEN ReservationAddress.FirstName = '' THEN '' ELSE ', ' + ReservationAddress.FirstName END AS FullName
  FROM #tab
  INNER JOIN Folios WITH (NOLOCK) ON Folios.FolioNumber = #tab.FolioNumber
  LEFT OUTER JOIN ReservationAddress WITH (NOLOCK) ON ReservationAddress.AddressNumber = Folios.ReservationAddressNumber
  WHERE ISNULL(AllAmount, 0) - ISNULL(DepositAmount, 0) <> ISNULL(InhouseAmount, 0)
/*
  SELECT #tab.FolioNumber, #tab.AllAmount-#tab.DepositAmount AS DebtorAmount, #tab.InhouseAmount,
  ReservationAddress.LastName + CASE WHEN ReservationAddress.FirstName = '' THEN '' ELSE ', ' + ReservationAddress.FirstName END AS FullName
  FROM #tab
  INNER JOIN Folios WITH (NOLOCK) ON Folios.FolioNumber = #tab.FolioNumber
  LEFT OUTER JOIN ReservationAddress WITH (NOLOCK) ON ReservationAddress.AddressNumber = Folios.ReservationAddressNumber
  WHERE 
  (
    (DepositAmount IS NOT NULL AND AllAmount <> DepositAmount) OR
    (InhouseAmount IS NOT NULL AND AllAmount <> InhouseAmount)
  )
*/
END

DROP TABLE #tab