CREATE PROC [dbo].[sp_HIX_GetPrescriptionByID] @PrescriptionId NUMERIC
AS
DECLARE @PharmacistFounder NVARCHAR(MAX);
SELECT @PharmacistFounder = gs.Value
FROM dbo.GeneralSetting gs
WHERE gs.Parameter = 'HIX_PharmacistFounderInfo';
DECLARE @Discount MONEY,
        @Subsidy MONEY;

SELECT @Subsidy = [0],
       @Discount = [1]
FROM
(
    SELECT Price,
           IsFdoDiscount
    FROM dbo.Over_Under_Factor_Drug d
        JOIN Over_Under dd
            ON dd.AutoId = d.Code_Over_Under
    WHERE Id_Havaleh = @PrescriptionId
          AND d.Type = 0
) AS SourceTable
PIVOT
(
    SUM(Price)
    FOR IsFdoDiscount IN ([0], [1])
) AS discount;

SELECT P.Id_Havaleh [PrescriptionId],
       P.Tarikh_Paziresh [AdmissionDate],
       P.Nezam_No [AttendingDoctorInfoMedicalCouncilCode],
       S.Hix_Code [AttendingDoctorInfoSpeciality],
       P.Note_Code [InsuranceNumber],
       P.Tarikh_Etebar [InsuranceBookletExpirationDate],
       P.Page_No [InsuranceBookletPageNumber],
       P.Resive_Name [PatientInfoFullName],
       [PatientInfoPatientId] = CASE
                                    WHEN N.Meli_Card_No IS NULL
                                         OR N.Meli_Card_No = '' THEN
                                        '0123456789'
                                    ELSE
                                        N.Meli_Card_No
                                END,
       [PatientInfoBirthDate] = CASE
                                    WHEN LEN(CAST(Age AS VARCHAR(4))) = 2 THEN
                                        dbo.ShamsiToMiladi('13' + CAST(N.Age AS VARCHAR(2)) + '/01/01')
                                    WHEN LEN(CAST(Age AS VARCHAR(4))) = 4 THEN
                                        dbo.ShamsiToMiladi(CAST(N.Age AS VARCHAR(4)) + '/01/01')
                                    ELSE
                                        GETDATE()
                                END,
       PatientInfoMobielNumber = CASE
                                     WHEN (N.Mobile IS NULL)
                                          OR (N.Mobile = '') THEN
                                         '09000000000'
                                     ELSE
                                         N.Mobile
                                 END,
       patientInfoGenderGender = CASE
                                     WHEN N.TypeSex = '0' THEN
                                         1
                                     WHEN N.TypeSex = '1' THEN
                                         0
                                     ELSE
                                         2
                                 END,
       INS.Drug_Code [PharmacyInfoPharmacyCode],
       PH.MedicalCode [tMedicalCouncilCode],
       @PharmacistFounder [PharmacyInfoPharmacistFounderInfo],
       PT.NationalCode [PharmacyInfoDispenserInfo],
       P.TotPriceDaryafti [PrescriptionCostInfoTotalCost],
       P.TotPriceFaniBimar + P.TotPriceFaniSazman [PrescriptionCostInfoTechnicalCost],
       ISNULL(@Discount, 0) [PrescriptionCostInfoDiscount],
       ISNULL(@Subsidy, 0) Subsidy,
       P.TotPriceBimar [PrescriptionCostInfoPayableByPatient],
       P.TotPriceFaniBimar [PrescriptionCostInfoAutomation],
       P.Tarikh_Noskheh [DispensedPrescriptionPrescriptionDate],
       INS.Hix_Code [InsuranceOrganizationCode],
       P.Nu_Forosh DocumentNumber
FROM dbo.DrugH P WITH (NOLOCK)
    INNER JOIN dbo.Notebimeh N WITH (NOLOCK)
        ON N.Note_Code = P.Note_Code
           AND N.Sazman_Code = P.Sazman_Code
    INNER JOIN dbo.Sahmiyeh INS
        ON INS.Sazman_Code = P.Sazman_Code
    INNER JOIN Grade S
        ON S.Grade_Code = P.Grade_Code
    LEFT JOIN dbo.DefinePharmacyTechnicalAndPharmacist PH
        ON PH.UserName = P.CheckU
           AND PH.[Status] = 0
    LEFT JOIN dbo.DefinePharmacyTechnicalAndPharmacist PT
        ON PT.UserName = P.[User_id]
           AND PT.[Status] = 1
WHERE P.Id_Havaleh = @PrescriptionId;

SELECT PD.Id_Havaleh [PrescriptionId],
       G.Meli_Code [AcceptedMedicationItemInfoGenericCode],
       K_Qty1 [AcceptedMedicationItemInfoMedicationCount],
       [CheckedOutMedicationItemInfoNationalDrugCode] = CASE
                                                            WHEN G.Barcode IS NULL
                                                                 OR G.Barcode = '' THEN
                                                                G.Meli_Code
                                                            ELSE
                                                                G.Meli_Code
                                                        END,
       PD.K_Qty1 [AcceptedMedicationItemInfoDeliveredMedicationCount],
       P.Tarikh_Paziresh [CheckedOutMedicationItemInfoMedicationDeliverDate],
       PD.Price_Forosh * K_Qty1 [CostsTotalCost],
       [CostsInsuranceContribution] = CASE
                                          WHEN PD.BimarPercent > 0 THEN
                                              ROUND(PD.Price_Forosh * PD.K_Qty1 * (100 - PD.BimarPercent) / 100, 0)
                                          ELSE
                                              ROUND(PD.Price_Forosh * PD.K_Qty1 * (100 - INS.Bimar_Percent) / 100, 0)
                                      END,
       [CostsPatientContribution] = CASE
                                        WHEN PD.BimarPercent > 0 THEN
                                            ROUND(PD.Price_Forosh * PD.K_Qty1 * PD.BimarPercent / 100, 0)
                                        ELSE
                                            ROUND(PD.Price_Forosh * PD.K_Qty1 * INS.Bimar_Percent / 100, 0)
                                    END,
       PD.Tot_Differ [CostsDifferenceOfInsuranceCoverAndPrice],
       [CostsPayableByPatient] = CASE
                                     WHEN PD.BimarPercent > 0 THEN
                                         ROUND(PD.Price_Forosh * PD.K_Qty1 * PD.BimarPercent / 100, 0)
                                     ELSE
                                         ROUND(PD.Price_Forosh * PD.K_Qty1 * INS.Bimar_Percent / 100, 0)
                                 END,
       [FrequencyUsageContent] = CASE
                                     WHEN (FR.Code IS NULL)
                                          OR (FR.Code = '') THEN
                                         N'هر 8 ساعت يک بار'
                                     ELSE
                                         FR.PersianMeaning
                                 END
FROM dbo.DrugHavaleh PD WITH (NOLOCK)
    INNER JOIN dbo.DrugH P WITH (NOLOCK)
        ON P.Id_Havaleh = PD.Id_Havaleh
    LEFT JOIN dbo.MedicationTerminology FR WITH (NOLOCK)
        ON FR.Code = PD.FrequencyCode
           AND FR.Type = 1
    INNER JOIN dbo.KalaId G
        ON G.K_Code = PD.K_Code
    INNER JOIN dbo.Sahmiyeh INS
        ON INS.Sazman_Code = P.Sazman_Code
WHERE PD.Id_Havaleh = @PrescriptionId
      AND PD.[Status] IN ( '0', '2', '4', '5', '6', '8', '9' );