using System;

using Newtonsoft.Json;

#nullable enable
namespace Hims.Infrastructure.Services
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Dapper;
    using Domain.Configurations;
    using Domain.Repositories.UnitOfWork;
    using Domain.Services;
    using Shared.Library;

    using Hims.Shared.Library.Enums;
    using Hims.Shared.EntityModels;
    using Admission = Hims.Shared.UserModels.ServiceOrder.Admission;
    using Hims.Shared.UserModels;
    using Hims.Shared.UserModels.Laboratory;
    using Hims.Shared.UserModels.Scan.ScanMachine;
    using Hims.Shared.UserModels.Filters;
    using Hims.Domain.Entities;
    using System.Collections;
    using System.Security.Cryptography;
    using Hims.Shared.UserModels.Labs;

    /// <inheritdoc />
    public class ResourceServices : IResourceService
    {
        /// <summary>
        /// The unit of work.
        /// </summary>
        private readonly IUnitOfWork unitOfWork;

        /// <summary>
        /// The document helper.
        /// </summary>
        private readonly IAmazonS3Configuration amazonS3Configuration;

        /// <summary>
        /// The running environment
        /// </summary>
        private readonly IRunningEnvironment runningEnvironment;
        private object locationId;

        /// <summary>
        /// Initializes a new instance of the <see cref="ResourceServices"/> class.
        /// </summary>
        /// <param name="unitOfWork">
        /// The unit of work.
        /// </param>
        /// <param name="amazonS3Configuration">
        /// The amazon S3 configuration.
        /// </param>
        public ResourceServices(IUnitOfWork unitOfWork, IAmazonS3Configuration amazonS3Configuration, IRunningEnvironment runningEnvironment)
        {
            this.unitOfWork = unitOfWork;
            this.amazonS3Configuration = amazonS3Configuration;
            this.runningEnvironment = runningEnvironment;
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> RolesAsync()
        {
            var where = $@" WHERE ""Active"" IS TRUE";
            var query = $@"SELECT ""RoleId"" AS ""Id"", ""RoleName"" AS ""Value"" FROM ""Role"" {where} ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> RolesWithOutPatient()
        {
            var where = $@" WHERE ""Active"" IS TRUE and ""RoleId""<>4 ";

            var query = $@"SELECT ""RoleId"" AS ""Id"", ""RoleName"" AS ""Value"" FROM ""Role"" {where} ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        /// <inheritdoc />
        public Task<IEnumerable<Resource>> CountriesAsync()
        {
            var where = $@" WHERE ""Active"" IS TRUE";
            var query = $@"SELECT ""CountryId"" AS ""Id"", ""CountryName"" AS ""Value"", ""CountryCode"" AS ""OptionalText"" FROM ""Country"" {where} ORDER BY 1 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public async Task<IEnumerable<Resource>> LocationsAsync()
        {
            var query = $@"SELECT
	                        ""LocationId"" ""Id"",
	                        ""Name"" ""Name""
                        FROM
	                        ""Location"" order by ""Name"" asc";

            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> LogTypesAsync()
        {
            var where = $@" WHERE ""Active"" IS TRUE";
            var query = $@"SELECT ""LogTypeId"" AS ""Id"", ""LogTypeName"" AS ""Value"" FROM ""LogType"" {where} ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> DepartmentsAsync(int? providerId, int? locationId)
        {
            var where = $@" WHERE 1=1 ";

            var join = " ";
            var joinProvider = " ";
            if (providerId != null)
            {
                joinProvider = $@"left join ""Provider"" p on d.""DepartmentId"" = p.""DepartmentId"" ";
                where += $@" and p.""ProviderId"" = {providerId}";
            }
            if (locationId > 0)
            {
                join = $@"left join ""LocationDepartmentMap"" LDM on LDM.""DepartmentId"" = d.""DepartmentId"" ";
                //where += $@" and LDM.""LocationId"" = {locationId}";
            }
            var query = $@"select DISTINCT d.""DepartmentName"" as ""Value"",d.""DepartmentId"" as ""Id"" from ""Department"" d {joinProvider} {join} {where} ";

            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> DoctorSpecializationAsync(int? providerId, int? locationId)
        {
            var where = $@" WHERE 1=1 ";


            if (providerId != null)
            {
                where += $@" and prl.""ProviderId"" = {providerId}";
            }
            //if (locationId > 0)
            //{
            //    join = $@" join ""LocationDepartmentMap"" LDM on LDM.""DepartmentId"" = d.""DepartmentId"" ";
            //    where += $@" and LDM.""LocationId"" = {locationId}";
            //}
            var query = $@"SELECT DISTINCT  on (prl.""ProviderId"", s.""SpecializationId"")prl.""FullName"" as ""OptionalText"",prl.""ProviderId"" as ""OptionalId""
                            , s. ""SpecializationId"" as ""Id"", s.""SpecializationName"" as ""Value""
                           FROM ""Provider"" prl
						   join ""Specialization"" s on s.""SpecializationId"" = ANY (prl.""Specializations"")
						   {where} ";

            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }


        /// <inheritdoc />
        public Task<IEnumerable<Resource>> SurgeryTypesAsync()
        {
            var query = $@"SELECT DISTINCT ""SurgeryName"" as ""Value"",""SurgeryTypeId"" as ""Id"" FROM ""SurgeryType"" ";

            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> AppointmentsAsync(string? searchParam)
        {
            var where = " WHERE 1 = 1 ";

            if (!string.IsNullOrEmpty(searchParam))
            {
                where += $@" AND TRIM(UPPER(a.""AppointmentNo"")) ILIKE '%{searchParam.Trim().ToUpper()}%' AND a.""Active"" IS TRUE";
            }

            var query = $@"SELECT DISTINCT a.""AppointmentId"" AS ""Id"", a.""AppointmentNo"" AS ""Value""
                                FROM ""Appointment"" a {where} ORDER BY 1 ASC";

            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> PatientsAsync(string? searchParam, int? providerId, bool? isBabyRegistration)
        {
            var where = " WHERE 1 = 1 ";

            if (!string.IsNullOrEmpty(searchParam))
            {
                where += $@" AND (TRIM(UPPER(pat.""FullName"")) ILIKE '%{searchParam.Trim().ToUpper()}%' OR pat.""Mobile"" ILIKE '%{searchParam.Trim().ToUpper()}%' OR pat.""UMRNo"" ILIKE '%{searchParam.Trim().ToUpper()}%') and case when pat.""TempPatient"" = TRUE THEN pat.""HowDidYouKnowId"" <> 11 ELSE 1 = 1 END AND pat.""Active"" IS TRUE";
            }
            if (isBabyRegistration == true)
            {
                where += $@" and pat.""IsBabyRegistration"" is false or pat.""IsBabyRegistration"" is null ";
            }
            //var query = $@"SELECT DISTINCT pat.""PatientId"" AS ""Id"", pat.""FullName"" AS ""Value"",pat.""Mobile"" as ""OptionalText2"",pat.""UMRNo"" as ""OptionalText1"",
            //                    (CASE WHEN pat.""ThumbnailUrl"" IS NOT NULL THEN CONCAT('{this.amazonS3Configuration.BucketURL}', pat.""Guid"", '/', pat.""ThumbnailUrl"") ELSE NULL END) AS ""OptionalText""
            //                    ,concat(pat.""FullName"",pat.""Mobile"",pat.""UMRNo"") as ""Name""
            //                    FROM ""Patient"" pat {where} ORDER BY 2 ASC";

            var query = $@"SELECT DISTINCT pat.""PatientId"" AS ""Id"", pat.""FullName"" AS ""Value"",pat.""Mobile"" as ""OptionalText2"",pat.""UMRNo"" as ""OptionalText1"",
                                pat.""Email"" AS ""OptionalText3""--,pat.""Age"" AS ""OptionalData"",pat.""PaymentStatus"" AS ""Status""
                                ,concat(pat.""FullName"",pat.""Mobile"",pat.""UMRNo"",pat.""Email"") as ""Name""
                                FROM ""Patient"" pat {where} ORDER BY 2 ASC";

            if (providerId != null)
            {
                where += $@" AND (A.""ProviderId"" = {providerId} OR pat.""CreatedBy"" = (Select ""Account"".""AccountId"" FROM ""Account"" WHERE ""Account"".""ReferenceId"" = {providerId} AND ""Account"".""RoleId"" = {(int)Roles.Provider} AND ""Account"".""Active"" IS TRUE)) ";

                query = $@"SELECT DISTINCT pat.""PatientId"" AS ""Id"", pat.""FullName"" AS ""Value"",pat.""Mobile"" as ""OptionalText2"",
                                pat.""ThumbnailUrl"" AS ""OptionalText""
                                FROM ""Patient"" pat
                                LEFT JOIN ""Country"" C on C.""CountryId"" = pat.""CountryId"" AND C.""Active"" IS TRUE
                                LEFT JOIN ""Account"" ACT on ACT.""ReferenceId"" = pat.""PatientId"" AND ACT.""RoleId"" = {(int)Roles.Patient} AND ACT.""Active"" IS TRUE
                                LEFT JOIN ""Appointment"" A on A.""PatientId"" = pat.""PatientId""
                                {where} ORDER BY 2 ASC";
            }

            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> PatientsScanAsync(string? searchParam)
        {
            var where = " WHERE 1 = 1 ";

            if (!string.IsNullOrEmpty(searchParam))
            {
                where += $@" AND (TRIM(UPPER(pat.""FullName"")) ILIKE '%{searchParam.Trim().ToUpper()}%' OR pat.""Mobile"" ILIKE '%{searchParam.Trim().ToUpper()}%' OR pat.""UMRNo"" ILIKE '%{searchParam.Trim().ToUpper()}%') AND pat.""Active"" IS TRUE";
            }
            var query = $@"SELECT DISTINCT pat.""PatientId"" AS ""Id"", pat.""FullName"" AS ""Value"",pat.""UMRNo"" as ""OptionalText1"",pat.""Mobile"" as ""OptionalText2"",
                                pat.""Email"" AS ""OptionalText3"",pat.""Age"" AS ""OptionalData"",pat.""Gender"",pat.""PaymentStatus"" AS ""Status""
                                ,concat(pat.""FullName"",pat.""Mobile"",pat.""UMRNo"",pat.""Email"") as ""Name""
                                FROM ""Patient"" pat {where} ORDER BY 2 ASC";

            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<FeedbackModel>> PatientAsync(FeedbackModel model)
        {

            var query = $@"SELECT DISTINCT pat.""PatientId"", pat.""FullName"",pat.""Mobile"" FROM ""Patient"" pat where ""Mobile"" = '{model.Mobile}'";

            return this.unitOfWork.Current.QueryAsync<FeedbackModel>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<PatientModel>> FetchPatientsAllAsync(string? searchParam, int? providerId)
        {
            var where = " WHERE 1 = 1 ";

            if (!string.IsNullOrEmpty(searchParam))
            {
                where += $@" AND (TRIM(UPPER(pat.""FullName"")) ILIKE '%{searchParam.Trim().ToUpper()}%' OR pat.""Mobile"" ILIKE '%{searchParam.Trim().ToUpper()}%')  AND pat.""Active"" IS TRUE";
            }

            var query = $@"SELECT DISTINCT pat.""PatientId"",pat.""FullName"",pat.""Mobile"",pat.""Gender"",pat.""DateOfBirth"",pat.""Age"",
                                (CASE WHEN pat.""ThumbnailUrl"" IS NOT NULL THEN CONCAT('{this.amazonS3Configuration.BucketURL}', pat.""Guid"", '/', pat.""ThumbnailUrl"") ELSE NULL END) AS ""OptionalText""
                                FROM ""Patient"" pat {where} ORDER BY 2 ASC";

            if (providerId != null)
            {
                where += $@" AND (A.""ProviderId"" = {providerId} OR pat.""CreatedBy"" = (Select ""Account"".""AccountId"" FROM ""Account"" WHERE ""Account"".""ReferenceId"" = {providerId} AND ""Account"".""RoleId"" = {(int)Roles.Provider} AND ""Account"".""Active"" IS TRUE)) ";

                query = $@"SELECT DISTINCT pat.""PatientId"",pat.""FullName"",pat.""Mobile"",pat.""Gender"",pat.""DateOfBirth"",pat.""Age"",
                                (CASE WHEN pat.""ThumbnailUrl"" IS NOT NULL THEN CONCAT('{this.amazonS3Configuration.BucketURL}', pat.""Guid"", '/', pat.""ThumbnailUrl"") ELSE NULL END) AS ""OptionalText""
                                FROM ""Patient"" pat
                                LEFT JOIN ""Country"" C on C.""CountryId"" = pat.""CountryId"" AND C.""Active"" IS TRUE
                                LEFT JOIN ""Account"" ACT on ACT.""ReferenceId"" = pat.""PatientId"" AND ACT.""RoleId"" = {(int)Roles.Patient} AND ACT.""Active"" IS TRUE
                                LEFT JOIN ""Appointment"" A on A.""PatientId"" = pat.""PatientId""
                                {where} ORDER BY 2 ASC";
            }

            return this.unitOfWork.Current.QueryAsync<PatientModel>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> ServicesAsync()
        {
            var where = $@" WHERE S.""Active"" IS TRUE";
            var query = $@"SELECT S.""ServiceId"" AS ""Id"", S.""ServiceName"" AS ""Value"" ,(case when I.""IconName"" is not null then CONCAT('{this.amazonS3Configuration.BucketURL}' ,I.""IconName"") else null end )  AS ""OptionalText"" FROM ""Service"" S left join ""Icons"" I on I.""IconsId"" = S.""ServiceIconId"" {where} ORDER BY S.""Priority"" ASC,S.""ServiceName"" ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> SpecializationsAsync()
        {
            var where = $@" WHERE S.""Active"" IS TRUE";
            var query = $@"SELECT ""SpecializationId"" AS ""Id"", ""SpecializationName"" AS ""Value"" ,I.""IconName"" AS ""OptionalText"",(CASE WHEN I.""IconName"" IS NOT NULL THEN CONCAT(I.""IconName"") ELSE NULL END) AS ""OptionalText1"" FROM ""Specialization"" S
                            left join ""Icons"" I on I.""IconsId"" = S.""SpecializationIconId"" {where} ORDER BY ""Priority"" ASC,""SpecializationName"" ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> InsuranceCompaniesAsync()
        {
            var where = $@" WHERE ""Active"" IS TRUE";
            var query = $@"SELECT ""InsuranceCompanyId"" AS ""Id"", ""FullName"" AS ""Value"" FROM ""InsuranceCompany"" {where} ORDER BY 1 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> LabOrderAsync()
        {
            var query = $@"SELECT ""LabOrderId"" AS ""Id"", ""Name"" AS ""Value"" FROM ""LabOrder""  ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> RadiologyAsync()
        {
            var query = $@"SELECT ""RadiologyId"" AS ""Id"", ""Name"" AS ""Value"" FROM ""Radiology""  ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> Relationships()
        {
            var query = $@"SELECT ""RelationsId"" AS ""Id"", ""RelationName"" AS ""Value"",""RO"" as ""Name"" FROM ""Relations""  ORDER BY 1 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public List<Resource> DocumentCategories() => new List<Resource>
                                                          {
                                                              new Resource { Id = 1, Value = "Id Proof" },
                                                              new Resource { Id = 2, Value = "Laboratory" },
                                                              new Resource { Id = 3, Value = "Radiology" },
                                                              new Resource { Id = 4, Value = "Prescription" },
                                                              new Resource { Id = 5, Value = "Medical History Record" },
                                                              new Resource { Id = 6, Value = "Others" }
                                                              //new Resource { Id = 3, Value = "Discharge Summary" },
                                                              //new Resource { Id = 4, Value = "Operative Report" },
                                                              //new Resource { Id = 7, Value = "Medical Test" },
                                                              //new Resource { Id = 8, Value = "Mental Status Examination" },
                                                              //new Resource { Id = 9, Value = "Progress Notes" },
                                                              //new Resource { Id = 10, Value = "Medication Records" },
                                                              //new Resource { Id = 11, Value = "Referral Summary" },
                                                              //new Resource { Id = 12, Value = "Physician's Order Sheet" },
                                                              //new Resource { Id = 13, Value = "Graphic Sheet" },
                                                              //new Resource { Id = 14, Value = "Full Transcript" },                                                              
                                                          }.OrderBy(m => m.Value).ToList();

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> ProviderAppointmentDatesAsync(int providerId)
        {
            var where = $@" WHERE ""ProviderId"" = '{providerId}' AND ""Active"" IS TRUE";
            var query = $@"SELECT ""AppointmentId"" AS ""Id"", ""AppointmentDate"" AS ""Value"" FROM ""Appointment"" {where} ORDER BY 1 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> ICDCodesAsync(string searchParam)
        {
            var where = " WHERE 1= 1 ";
            if (!string.IsNullOrEmpty(searchParam))
            {
                where += $@" AND TRIM(UPPER(""Description"")) ILIKE '{searchParam.Trim().ToUpper()}%'";
            }

            var query = $@"SELECT ""ICDCodeId"" AS ""Id"", ""Code"" AS ""Value"", ""Description"" AS ""OptionalText"" FROM ""ICDCode"" {where} ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> CPTCodesAsync(string searchParam)
        {
            var where = " WHERE 1= 1 ";
            if (!string.IsNullOrEmpty(searchParam))
            {
                where += $@" AND TRIM(UPPER(""Description"")) ILIKE '{searchParam.Trim().ToUpper()}%'";
            }

            var query = $@"SELECT ""CPTCodeId"" AS ""Id"", ""Code"" AS ""Value"", ""Description"" AS ""OptionalText"" FROM ""CPTCode"" {where} ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> LookupsAsync(string searchParam)
        {
            var where = " WHERE 1= 1 ";
            if (!string.IsNullOrEmpty(searchParam))
            {
                if (searchParam != "null")
                {
                    where += $@" AND TRIM(UPPER(""Name"")) ILIKE '{searchParam.Trim().ToUpper()}%'";
                }
            }

            var query = $@"SELECT ""LookupId"" AS ""Id"", ""Name"" AS ""Value"", ""Name"" AS ""OptionalText"" FROM ""Lookup""  {where} ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> LookupValuesAsync(string searchParam, int? lookupId)
        {
            var where = "where 1=1";
            if (lookupId != 0)
            {
                where = $@" and WHERE ""LookupId"" = '{lookupId}' ";
            }
            if (!string.IsNullOrEmpty(searchParam))
            {
                where += $@" AND TRIM(UPPER(""Name"")) ILIKE '{searchParam.Trim().ToUpper()}%'";
            }

            var query = $@"SELECT ""LookupValueId"" AS ""Id"", ""Name"" AS ""Value"", ""Name"" AS ""OptionalText"" FROM ""LookupValue"" {where} ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> LookupValuesBasedOnLookupNameAsync(string lookupValueName)
        {
            var where = " WHERE 1= 1 ";
            if (!string.IsNullOrEmpty(lookupValueName))
            {
                where += $@" AND ""LookupId"" IN (Select DISTINCT ""LookupId"" FROM ""Lookup"" WHERE TRIM(UPPER(""Name"")) = '{lookupValueName.Trim().ToUpper()}')";
            }

            var query = $@"SELECT ""LookupValueId"" AS ""Id"", ""Name"" AS ""Value"", ""Name"" AS ""OptionalText"" FROM ""LookupValue"" {where} ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> FetchProblemListAsync(string searchParam)
        {
            var where = " WHERE 1= 1 ";
            if (!string.IsNullOrEmpty(searchParam))
            {
                where += $@"AND TRIM(UPPER(""Name"")) ILIKE '%{searchParam.Trim().ToUpper()}%' ";
            }

            var query = $@"SELECT ""ProblemListId"" AS ""Id"", ""Name"" AS ""Value"", ""Name"" AS ""OptionalText"" FROM ""ProblemList"" {where} ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> FetchProviders(int? departmentId, int? locationId)
        {
            var where = $@" WHERE pr2.""Active"" = true and prl.""Active"" is true";
            if (departmentId != null)
            {
                where += $@" AND pr2.""DepartmentId"" = {departmentId} ";
            }
            if (locationId != null)
            {
                where += $@" and prl.""LocationId""= {locationId}";
            }

            //var query = $@"SELECT DISTINCT  prl.""ProviderLocationId"" as ""OptionalData"",pr2.""FullName"" as ""Value"",
            //d.""DepartmentName"" AS ""OptionalText"", d.""DepartmentId"" AS ""OptionalId"",pr2.""ProviderId"" AS ""Id"",
            //(CASE WHEN pr2.""ThumbnailUrl"" IS NOT NULL THEN CONCAT('{this.amazonS3Configuration.BucketURL}', pr2.""Guid"", '/', pr2.""ThumbnailUrl"") ELSE NULL END) AS ""OptionalText2""
            //  FROM ""ProviderLocation"" prl
            //JOIN ""Location"" pral on pral.""LocationId"" = prl.""LocationId"" AND pral.""Active"" IS TRUE
            //JOIN ""Practice"" pra on pra.""PracticeId"" = pral.""PracticeId"" AND pra.""Active"" IS TRUE
            //JOIN ""Provider"" pr2 on pr2.""ProviderId"" = prl.""ProviderId"" and pr2.""Active"" is true
            //JOIN ""Department"" d on d.""DepartmentId"" = pr2.""DepartmentId""
            //{where}  ORDER BY pr2.""FullName"" ";

            //var query = $@" SELECT DISTINCT pr2.""ProviderId"" AS ""Id"",pr2.""FullName"" as ""Value"", --prl.""ProviderAvailabilityId"" as ""OptionalData"" ,
            //                d.""DepartmentName""  AS ""OptionalText"" , d.""DepartmentId"" AS ""OptionalId"",  prl.""LocationId"",
            //                (CASE WHEN pr2.""ThumbnailUrl"" IS NOT NULL THEN CONCAT('{this.amazonS3Configuration.BucketURL}', pr2.""Guid"", '/', pr2.""ThumbnailUrl"") ELSE NULL END) AS ""OptionalText2"",A.""UserName"" AS ""OptionalText1""
            //                from ""Provider"" pr2
            //                join ""ProviderAvailability"" prl on   prl.""ProviderId"" = pr2.""ProviderId""
            //                join ""Specialization"" s on s.""SpecializationId"" = ANY(pr2.""Specializations"") and s.""Active"" = true
            //                join ""Location"" l on l.""LocationId"" = prl.""LocationId""
            //                JOIN ""Department"" d on d.""DepartmentId"" = pr2.""DepartmentId""
            //                JOIN ""Practice"" pra on pra.""PracticeId"" = l.""PracticeId"" AND pra.""Active"" IS TRUE
            //                left join ""Account"" A on A.""ReferenceId"" = pr2.""ProviderId"" and A.""RoleId"" = {(int)Roles.Provider}
            //                   { where}  ORDER BY pr2.""FullName"" ";

            // Doctor names are repeating based on there SpecializationId, so removed this so that doctor name is shown only once.
            //var query = $@"SELECT DISTINCT  on (pr2.""ProviderId"", s.""SpecializationId"") prl.""ProviderAvailabilityId"" ,pr2.""FullName"" as ""Value""
            //, d.""DepartmentName"" AS ""OptionalText"" , d.""DepartmentId"" AS ""OptionalId""
            //,pr2.""ProviderId"" AS ""Id""
            //, s. ""SpecializationId""  AS ""OptionalData"", s.""SpecializationName"" AS ""OptionalText1""
            //, prl.""LocationId"", prl.""ConsultationTypeId""
            //                           FROM ""ProviderAvailability"" prl
            //                           JOIN ""Provider"" pr2 on pr2.""ProviderId"" = prl.""ProviderId"" and pr2.""Active"" is true
            //						   join ""Specialization"" s on s.""SpecializationId"" = ANY (pr2.""Specializations"")
            //                           JOIN ""Location"" pral on pral.""LocationId"" = prl.""LocationId"" AND pral.""Active"" IS TRUE
            //                           JOIN ""Practice"" pra on pra.""PracticeId"" = pral.""PracticeId"" AND pra.""Active"" IS TRUE
            //						   JOIN ""Department"" d on d.""DepartmentId"" = pr2.""DepartmentId""
            //						   { where} and s.""Active"" = true
            //						 ORDER BY pr2.""ProviderId"" ";

            var query = $@"SELECT DISTINCT  on (pr2.""ProviderId"") prl.""ProviderAvailabilityId"" ,pr2.""FullName"" as ""Value""
            , d.""DepartmentName"" AS ""OptionalText"" , d.""DepartmentId"" AS ""OptionalId""
            ,pr2.""ProviderId"" AS ""Id""
            , s. ""SpecializationId""  AS ""OptionalData"", s.""SpecializationName"" AS ""OptionalText1""
            , prl.""LocationId"", prl.""ConsultationTypeId""
                                       FROM ""ProviderAvailability"" prl
                                       JOIN ""Provider"" pr2 on pr2.""ProviderId"" = prl.""ProviderId"" and pr2.""Active"" is true
            						   join ""Specialization"" s on s.""SpecializationId"" = ANY (pr2.""Specializations"")
                                       JOIN ""Location"" pral on pral.""LocationId"" = prl.""LocationId"" AND pral.""Active"" IS TRUE
                                       JOIN ""Practice"" pra on pra.""PracticeId"" = pral.""PracticeId"" AND pra.""Active"" IS TRUE
            						   JOIN ""Department"" d on d.""DepartmentId"" = pr2.""DepartmentId""
            						   {where} and s.""Active"" = true
            						 ORDER BY pr2.""ProviderId"" ";

            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> FetchProvider(int? providerId) //////wrong query/
        {
            var where = $@" WHERE pr2.""Active"" = true ";
            if (providerId != null)
            {
                where += $@" AND pr2.""ProviderId"" = {providerId} ";
            }
            var query = $@"SELECT DISTINCT pr2.""FullName"" as ""Value"", pr2.""FullName"" AS ""OptionalText"",pr2.""ProviderId"" AS ""Id"",(CASE WHEN pr2.""ThumbnailUrl"" IS NOT NULL THEN CONCAT('{this.amazonS3Configuration.BucketURL}', pr2.""Guid"", '/', pr2.""ThumbnailUrl"") ELSE NULL END) AS ""OptionalText2""
                           FROM ""ProviderLocation"" prl
                           JOIN ""PracticeLocation"" pral on pral.""PracticeLocationId"" = prl.""PracticeLocationId"" AND pral.""Active"" IS TRUE
                           JOIN ""Practice"" pra on pra.""PracticeId"" = pral.""PracticeId"" AND pra.""Active"" IS TRUE
                           JOIN ""Provider"" pr2 on pr2.""ProviderId"" = prl.""ProviderId"" {where} ORDER BY pr2.""FullName"" ";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> ProviderAsync(string searchParam, int? providerId)
        {
            var where = " WHERE 1= 1 ";

            if (!string.IsNullOrEmpty(searchParam))
            {
                where += $@" AND TRIM(UPPER(pat.""FullName"")) ILIKE '%{searchParam.Trim().ToUpper()}%' AND pat.""Active"" IS TRUE";
            }

            var query = $@"SELECT pat.""ProviderId"" AS ""Id"", pat.""FullName"" AS ""Value"",
                                (CASE WHEN pat.""ThumbnailUrl"" IS NOT NULL THEN CONCAT('{this.amazonS3Configuration.BucketURL}', pat.""Guid"", '/', pat.""ThumbnailUrl"") ELSE NULL END) AS ""OptionalText""
                                FROM ""Provider"" pat {where} ORDER BY 2 ASC";

            if (providerId != null)
            {
                where += $@" AND (A.""ProviderId"" = {providerId} OR pat.""CreatedBy"" = (Select ""Account"".""AccountId"" FROM ""Account"" WHERE ""Account"".""ReferenceId"" = {providerId} AND ""Account"".""RoleId"" = {(int)Roles.Provider} AND ""Account"".""Active"" IS TRUE)) ";

                query = $@"SELECT pat.""PatientId"" AS ""Id"", pat.""FullName"" AS ""Value"",
                                (CASE WHEN pat.""ThumbnailUrl"" IS NOT NULL THEN CONCAT('{this.amazonS3Configuration.BucketURL}', pat.""Guid"", '/', pat.""ThumbnailUrl"") ELSE NULL END) AS ""OptionalText""
                                FROM ""Patient"" pat
                                LEFT JOIN ""Country"" C on C.""CountryId"" = pat.""CountryId"" AND C.""Active"" IS TRUE
                                LEFT JOIN ""Account"" ACT on ACT.""ReferenceId"" = pat.""PatientId"" AND ACT.""RoleId"" = {(int)Roles.Patient} AND ACT.""Active"" IS TRUE
                                LEFT JOIN ""Appointment"" A on A.""PatientId"" = pat.""PatientId"" AND A.""Active"" IS TRUE
                                {where} ORDER BY 2 ASC";
            }

            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public async Task<IEnumerable<Resource>> ProviderWithChargesAsync(string searchParam, bool isAdmission)
        {
            var where = " WHERE 1= 1 ";

            if (!string.IsNullOrEmpty(searchParam))
            {
                where += $@" AND TRIM(UPPER(pat.""FullName"")) ILIKE '%{searchParam.Trim().ToUpper()}%' AND pat.""Active"" IS TRUE";
            }

            var query = $@"SELECT pat.""ProviderId"" AS ""Id"", pat.""FullName"" AS ""Value"",
                                (CASE WHEN pat.""ThumbnailUrl"" IS NOT NULL THEN CONCAT('{this.amazonS3Configuration.BucketURL}', pat.""Guid"", '/', pat.""ThumbnailUrl"") ELSE NULL END) AS ""OptionalText"",
                                location.""Availability"" AS ""OptionalText2""
                                FROM ""Provider"" pat
                                LEFT JOIN LATERAL (
		                            SELECT c.""Availability"" FROM ""ProviderLocation"" c
                                    WHERE pat.""ProviderId"" = c.""ProviderId""
		                            LIMIT 1
	                            ) location ON true
                                {where} ORDER BY 2 ASC";


            var records = await this.unitOfWork.Current.QueryAsync<Resource>(query);
            var providerWithChargesAsync = records.ToList();

            foreach (var record in providerWithChargesAsync)
            {
                if (string.IsNullOrEmpty(record.OptionalText2)) continue;

                var costs = JsonConvert.DeserializeObject<IEnumerable<Admission.ProviderCostModel>>(record.OptionalText2);
                var providerCostModels = costs.ToList();
                if (!providerCostModels.Any()) continue;

                var cost = providerCostModels.FirstOrDefault(x => x.Day == GetDay(DateTime.Now.DayOfWeek));
                if (cost != null)
                {
                    record.Cost = isAdmission
                        ? cost.InPatientCharges ?? 0
                        : cost.OutPatientCharges ?? 0;
                }
            }

            return providerWithChargesAsync;
        }

        private static int GetDay(DayOfWeek day)
        {
            return day switch
            {
                DayOfWeek.Monday => 1,
                DayOfWeek.Tuesday => 2,
                DayOfWeek.Wednesday => 3,
                DayOfWeek.Thursday => 4,
                DayOfWeek.Friday => 5,
                DayOfWeek.Saturday => 6,
                _ => 7
            };
        }

        /// <inheritdoc />
        public async Task<IEnumerable<Resource>> MastersAsync(string searchParam)
        {
            searchParam = !string.IsNullOrEmpty(searchParam) ? searchParam.ToUpper() : string.Empty;
            var query = $@"Select * from ""udf_fetchMasters""('{searchParam}');";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public async Task<IEnumerable<Resource>> Masters1Async(string searchParam, int? locationId)
        {
            var paramsString = "";

            paramsString += searchParam != null ? $@"'{searchParam.ToUpper()}'" : $@" null";
            paramsString += locationId != null ? $@", '{locationId}'" : $@", null";
            var query = $@"Select * from ""udf_fetchMastersloc""({paramsString});";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> PracticeLocationsAsync(int countryId)
        {
            var where = $@" WHERE prl.""Active"" = true AND prl.""CountryId"" = '{countryId}'";
            var query = $@"SELECT prl.""LocationId"" AS ""Id"", pra.""FullName"" as ""Value"", prl.""Name"" AS ""OptionalText"", c.""CurrencySymbol"" AS ""OptionalText2""
                                FROM ""Location"" prl
                                JOIN ""Country"" c on c.""CountryId"" = prl.""CountryId""
                                JOIN ""Practice"" pra on pra.""PracticeId"" = prl.""PracticeId"" AND pra.""Active"" IS TRUE
                                 {where} ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        public Task<IEnumerable<Resource>> PracticeAsync()
        {

            var query = $@"select ""PracticeId"" as ""Id"",""FullName"" as ""Value"" from ""Practice""";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        /// <inheritdoc />
        public Task<IEnumerable<Resource>> ProviderLocationsAsync(int providerId, int? specializationId, int? locationId)
        {
            var where = $@" WHERE prl.""ProviderId"" = '{providerId}'";
            if (locationId != null)
            {
                where += $@" and prl.""LocationId"" = {locationId} ";
            }
            if (specializationId != null)
            {
                where += $@" and s.""SpecializationId"" = {specializationId} ";
            }

            var query = $@"SELECT prl.""ProviderLocationId"" AS ""Id"", pra.""FullName"" as ""Value"", pral.""Name"" AS ""OptionalText""
                                FROM ""ProviderLocation"" prl
                                JOIN ""Location"" pral on pral.""LocationId"" = prl.""LocationId"" AND pral.""Active"" IS TRUE
                                JOIN ""Practice"" pra on pra.""PracticeId"" = pral.""PracticeId"" AND pra.""Active"" IS TRUE
                                join ""Provider"" p on p.""ProviderId"" = prl.""ProviderId""
                                join ""Specialization"" s on s.""SpecializationId"" = any(p.""Specializations"")
                                {where} ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public Task<IEnumerable<Resource>> DrugsAsync(string searchParam, string searchValue, string medicineSearchType)
        {
            var query = string.Empty;
            var where = " WHERE 1= 1 ";
            if (!string.IsNullOrEmpty(searchParam))
            {
                if (!string.IsNullOrEmpty(searchValue))
                {
                    if (searchValue == "StartsWith")
                    {
                        if (medicineSearchType == "MedicineName")
                        {
                            where += $@" AND TRIM(UPPER(""DrugName"")) ILIKE '{searchParam.Trim().ToUpper()}%'";
                        }
                        else
                        {
                            where += $@" AND TRIM(UPPER(""Composition"")) ILIKE '{searchParam.Trim().ToUpper()}%'";
                        }
                    }
                    else
                    {
                        if (medicineSearchType == "MedicineName")
                        {
                            where += $@" AND TRIM(UPPER(""DrugName"")) ILIKE '%{searchParam.Trim().ToUpper()}%'";
                        }
                        else
                        {
                            where += $@" AND TRIM(UPPER(""Composition"")) ILIKE '%{searchParam.Trim().ToUpper()}%'";
                        }
                    }
                }
            }

            if (!string.IsNullOrEmpty(medicineSearchType))
            {
                if (medicineSearchType == "MedicineName")
                {
                    query =
                       $@"SELECT ""DrugId"" as ""Id"",""Composition"" as ""OptionalText"" ,""DrugName"" as ""Value"" from ""Drug"" {where} ORDER BY 1 ASC LIMIT 20";
                }
                else
                {
                    query =
                        $@"SELECT ""DrugId"" as ""Id"",""Composition"" as ""Value"" ,""DrugName"" as ""OptionalText"" from ""Drug"" {where} ORDER BY 1 ASC LIMIT 20";
                }
            }

            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public Task<IEnumerable<Resource>> GeneralAdvicesAsync(int? providerId)
        {
            var where = " WHERE 1= 1 ";
            if (providerId != null)
            {
                where += $@" AND ""GeneralAdviceId"" in (SELECT UNNEST (string_to_array(""GeneralAdviceIds"", ',')::integer[]) FROM ""ProviderEncounter"" where ""ProviderId"" = {providerId})";
            }

            var query = $@"SELECT ""GeneralAdviceId"" AS ""Id"",""FullName"" AS ""Value"" FROM ""GeneralAdvice"" {where} ";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public Task<IEnumerable<Resource>> ICDCodesAsync(int? providerId)
        {
            var where = " WHERE 1= 1 ";
            if (providerId != null)
            {
                where += $@" AND ""ICDCodeId"" in (SELECT UNNEST (string_to_array(""ICDIds"", ',')::integer[]) FROM ""ProviderEncounter"" where ""ProviderId"" = {providerId})";
            }

            var query = $@"SELECT ""ICDCodeId"" AS ""Id"",""Code"" AS ""Value"", ""Description"" as ""OptionalText""  FROM ""ICDCode"" {where} ";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchBasedOnRole(int roleId, string searchParam)
        {
            var where = $@" where ""RoleId"" = {roleId}";
            if (!string.IsNullOrEmpty(searchParam))
            {
                where += $@" and ""FullName"" ilike '%{searchParam}%'";
            }

            var query = $@"Select ""FullName"" as ""Value"" , ""ReferenceId"" as ""OptionalText"" ,""AccountId"" as ""Id"" from ""Account"" {where} and ""Active"" is true order by ""Id"" desc ";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchNurses()
        {
            var query = $@"SELECT
	                        a.""FullName"" AS ""Value"",
	                        a.""ReferenceId"" AS ""OptionalText"",
	                        a.""AccountId"" AS ""Id""
                        FROM
	                        ""Account"" a
	                        JOIN ""Role"" r on r.""RoleId"" = a.""RoleId""
                        WHERE
	                        a.""Active"" IS TRUE AND r.""RoleConcept"" = 'N'
                        ORDER BY
	                        ""Id"" DESC";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchAllUsers()
        {
            var query = $@"Select a.""FullName"" as ""Value"" , r.""RoleName"" as ""OptionalText2"" ,a.""AccountId"" as ""Id"",
                        (CASE WHEN usr.""ThumbnailUrl"" IS NOT NULL THEN CONCAT('{this.amazonS3Configuration.BucketURL}', usr.""Guid"", '/', usr.""ThumbnailUrl"") ELSE NULL END) AS ""OptionalText""
                            from ""Account"" a
                            join ""User"" usr on usr.""UserId"" = a.""ReferenceId""
                            join ""Role"" r on r.""RoleId"" = a.""RoleId"" and lower(r.""RoleName"") <>'patient' and lower(r.""RoleName"") <>'Provider'
                            where a.""Active"" is true
                            order by a.""AccountId"" desc ";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public Task<IEnumerable<Resource>> LabOrdersAsync(int? providerId)
        {
            var where = " WHERE 1= 1 ";
            if (providerId != null)
            {
                where += $@" AND ""LabOrderValueId"" in (SELECT UNNEST (string_to_array(""LabOrderValueIds"", ',')::integer[]) FROM ""ProviderEncounter"" where ""ProviderId"" = {providerId})";
            }

            var query = $@"SELECT lov.""LabOrderValueId"" as ""Id"", lov.""OrderCode"" as ""Value"", lov.""Name"" as ""OptionalText"", lo.""Name"" as ""OptionalText2""
                            FROM ""LabOrderValue"" lov JOIN ""LabOrder"" lo ON lov.""LabOrderId"" = lo.""LabOrderId"" {where} ORDER BY  lo.""Name"", lov.""Name"" ";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public Task<IEnumerable<Resource>> RadiologyOrdersAsync(int? providerId)
        {
            var where = " WHERE 1= 1 ";
            if (providerId != null)
            {
                where += $@" AND ""RadiologyValueId"" in (SELECT UNNEST (string_to_array(""RadiologyValueIds"", ',')::integer[]) FROM ""ProviderEncounter"" where ""ProviderId"" = {providerId})";
            }

            var query = $@"SELECT rov.""RadiologyValueId"" AS ""Id"", rov.""OrderCode"" as ""Value"", rov.""Name"" as ""OptionalText"", ro.""Name"" as ""OptionalText2""
                            FROM ""RadiologyValue"" rov JOIN ""Radiology"" ro ON rov.""RadiologyId"" = ro.""RadiologyId"" {where} ORDER BY  ro.""Name"", rov.""Name"" ";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchAdminSuperAdminUsers()
        {
            var where = $@" where A.""RoleId"" not in (3,4)";

            var query = $@"Select A.""FullName"" as ""Value"" , R.""RoleName"" as ""OptionalText"" ,A.""AccountId"" as ""Id""from ""Account"" A
                                    join ""Role"" R on R.""RoleId"" = A.""RoleId""
                                    {where} and A.""Active"" is true order by ""Id"" desc ";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchLanguagesAsync()
        {
            var query = $@"SELECT ""Name"" as ""Value"" , ""LanguageId"" as ""Id""from ""Language"" WHERE ""Active"" is true order by ""LanguageId"" desc ";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchQuestionAsync()
        {
            var query = $@"SELECT ""Question"" as ""Value"" , ""QuestionFeedbackId"" as ""Id""from ""QuestionFeedback"" WHERE ""Active"" is true order by ""QuestionFeedbackId"" desc ";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchUsersAsync()
        {
            var query = $@"SELECT DISTINCT  usr.""FullName"" as ""Value"", usr.""UserId"" as ""Id"", rl.""RoleName"" as ""OptionalText2"" ,
                                (CASE WHEN usr.""ThumbnailUrl"" IS NOT NULL THEN CONCAT('https://s3.amazonaws.com/Hims.dev/', usr.""Guid"", '/', usr.""ThumbnailUrl"") ELSE NULL END) AS ""OptionalText"",act.""UserName"" AS ""OptionalText1""
                                FROM ""User"" usr
                                JOIN ""Account"" act ON act.""ReferenceId"" = usr.""UserId"" AND act.""RoleId"" IN ( select ""RoleId"" from ""Role"" where ""RoleId"" not in ({(int)Roles.Provider},{(int)Roles.Patient}))
                                LEFT JOIN ""Role"" rl ON rl.""RoleId"" = usr.""RoleId"" AND rl.""Active"" IS TRUE Order by usr.""UserId"" DESC";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchPatientAsync()
        {
            var query = $@"SELECT DISTINCT pat.""PatientId"" AS ""Id"", pat.""FullName"" AS ""Value"",pat.""Mobile"" as ""OptionalText2"",  pat.""UMRNo"" as ""OptionalText1"",
                                (CASE WHEN pat.""ThumbnailUrl"" IS NOT NULL THEN CONCAT('{this.amazonS3Configuration.BucketURL}', pat.""Guid"", '/', pat.""ThumbnailUrl"") ELSE NULL END) AS ""OptionalText""
                                FROM ""Patient"" pat ORDER BY pat.""PatientId"" ASC";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchDepartmentAsync()
        {
            var query = $@"SELECT DISTINCT ""DepartmentId"" AS ""Id"", ""DepartmentName"" AS ""Value"" FROM ""Department""
                ORDER BY ""DepartmentName"" ASC";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchProviderDepartmentAsync()
        {
            var query = $@"SELECT DISTINCT ""DepartmentId"" AS ""Id"", ""DepartmentName"" AS ""Value"" FROM ""Department""
               where ""DeptType""='Providers' ORDER BY ""DepartmentName"" ASC";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchPharmacyCategoriesAsync()
        {
            var query = $@"SELECT DISTINCT ""LookupValueId"" AS ""Id"", ""Name"" AS ""Value"", ""LookupId"" as ""OptionalText2""
                                FROM ""LookupValue""
								where ""LookupId"" = (Select ""LookupId"" from ""Lookup"" where ""Name""='PharmacyCategory')
								ORDER BY ""Name"" ASC";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchPharmacyCompaniesAsync()
        {
            var query = $@"SELECT DISTINCT ""CompanyId"" AS ""Id"", ""Name"" AS ""Value"", ""Location"" as ""OptionalText2""
                                FROM ""Company""  ORDER BY ""Name"" ASC";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchPharmacyProductsAsync(int? categoryId, string searchTerm)
        {
            var where = $@"where 1=1";

            if (categoryId != null)
            {
                where += $@" and ""CategoryId"" = {categoryId}";
            }

            if (!string.IsNullOrEmpty(searchTerm) && (searchTerm != "null"))
            {
                where += $@" and (""ProductName"" ILIKE '%{searchTerm}%' OR ""GenericName"" ILIKE '%{searchTerm}%')";
            }

            var query = $@"SELECT DISTINCT ""PharmacyProductId"" AS ""Id"", ""ProductName"" AS ""Value"", ""GenericName"" as ""OptionalText2"",""CategoryId"" as ""OptionalId""
                                FROM ""PharmacyProduct"" {where} ORDER BY ""ProductName"" ";

            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchPharmacyProductAsync(string CategoryName, string searchTerm)
        {
            var where = $@"where 1=1";

            //if (!string.IsNullOrEmpty(CategoryName))
            //{
            //    where += $@" and ""CategoryName"" = {CategoryName}";
            //}

            if (!string.IsNullOrEmpty(searchTerm))
            {
                where += $@" and (""ProductName"" ILIKE '%{searchTerm}%' OR ""GenericName"" ILIKE '%{searchTerm}%')";
            }

            var query = $@"SELECT DISTINCT p.""PharmacyProductId"" AS ""Id"", p.""ProductName"" AS ""Value"", p.""GenericName"" as ""OptionalText2"",p.""CategoryId"" as ""OptionalId"",ci.""Name"" ""OptionalText1""
                                FROM ""PharmacyProduct"" p
                                join ""LookupValue"" ci on ci.""LookupValueId"" = p.""CategoryId"" {where} ORDER BY p.""ProductName"" ASC limit 20";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchReceiptionistReportsAsync(string roleId)
        {
            var param = "";
            if (roleId != null)
            {
                param = @$"rol.""RoleId"" = {roleId}::int ";
            }
            else
            {
                param = "1=1";
            }
            var query = $@"SELECT DISTINCT acc.""AccountId"" as ""Id"",rol.""RoleName"" as ""OptionalText2"",acc.""FullName"" as ""Value"",(CASE WHEN usr.""ThumbnailUrl"" IS NOT NULL THEN CONCAT('{this.amazonS3Configuration.BucketURL}', usr.""Guid"", '/', usr.""ThumbnailUrl"") ELSE NULL END) AS ""OptionalText"" from ""User"" usr join ""Account"" acc on usr.""RoleId"" = acc.""RoleId"" join ""Role"" rol on usr.""RoleId"" = rol.""RoleId"" where {param} ";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchRolesAllAsync(string roleId)
        {
            var where = " where 1=1";
            if (!string.IsNullOrEmpty(roleId))
            {
                where += @$" and rol.""RoleId"" <> {roleId}::int";
            }
            var query = $@"SELECT DISTINCT acc.""AccountId"" as ""Id"",rol.""RoleName"" as ""OptionalText2"",acc.""FullName"" as ""Value""
from ""Account"" acc  join ""Role"" rol on acc.""RoleId"" = rol.""RoleId"" {where}";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> FetchInstructionsAsync()
        {
            var query = $@"SELECT LV.""LookupValueId"" AS ""Id"", LV.""Name"" AS ""Value"", L.""Name"" AS ""OptionalText"" FROM ""EncounterLookupValue"" LV
                            JOIN ""EncounterLookup"" L ON L.""LookupId"" = LV.""LookupId"" WHERE L.""LookupId"" in (1006, 1007, 1008) ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> EncounterLookupsAsync(string searchParam)
        {
            var where = " WHERE 1= 1 ";
            if (!string.IsNullOrEmpty(searchParam))
            {
                where += $@" AND TRIM(UPPER(""Name"")) ILIKE '{searchParam.Trim().ToUpper()}%'";
            }

            var query = $@"SELECT ""LookupId"" AS ""Id"", ""Name"" AS ""Value"", ""Name"" AS ""OptionalText"" FROM ""EncounterLookup""  {where} ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> EncounterLookupValuesAsync(string searchParam, int lookupId)
        {
            var where = $@" WHERE ""LookupId"" = '{lookupId}' ";
            if (!string.IsNullOrEmpty(searchParam))
            {
                where += $@" AND TRIM(UPPER(""Name"")) ILIKE '{searchParam.Trim().ToUpper()}%'";
            }

            var query = $@"SELECT ""LookupValueId"" AS ""Id"", ""Name"" AS ""Value"", ""Name"" AS ""OptionalText"" FROM ""EncounterLookupValue"" {where} ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> EncounterLookupValuesAsync(string lookupValueName)
        {
            var where = " WHERE 1= 1 ";
            if (!string.IsNullOrEmpty(lookupValueName))
            {
                where += $@" AND ""LookupId"" IN (Select DISTINCT ""LookupId"" FROM ""Lookup"" WHERE TRIM(UPPER(""Name"")) = '{lookupValueName.Trim().ToUpper()}')";
            }

            var query = $@"SELECT ""LookupValueId"" AS ""Id"", ""Name"" AS ""Value"", ""Name"" AS ""OptionalText"" FROM ""EncounterLookupValue"" {where} ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public async Task<List<Resource>> FetchPatientDoctorsAsync(int patientId, int? locationId)
        {
            var where = string.Empty;
            if (locationId != null)
            {
                where = $@" and prl.""LocationId"" = {locationId}";
            }
            var mainQuery = $@"SELECT DISTINCT pr2.""FullName"" as ""Value"", d.""DepartmentName"" AS ""OptionalText"", d.""DepartmentId"" AS ""OptionalId"",pr2.""ProviderId"" AS ""Id"",(CASE WHEN pr2.""ThumbnailUrl"" IS NOT NULL THEN CONCAT('{this.amazonS3Configuration.BucketURL}', pr2.""Guid"", '/', pr2.""ThumbnailUrl"") ELSE NULL END) AS ""OptionalText2""
                           FROM ""ProviderLocation"" prl
                           JOIN ""Location"" pral on pral.""LocationId"" = prl.""LocationId"" AND pral.""Active"" IS TRUE
                           JOIN ""Practice"" pra on pra.""PracticeId"" = pral.""PracticeId"" AND pra.""Active"" IS TRUE
                           JOIN ""Provider"" pr2 on pr2.""ProviderId"" = prl.""ProviderId""
                            JOIN ""Department"" d on d.""DepartmentId"" = pr2.""DepartmentId""  WHERE pr2.""Active"" = true {where} ";

            var doctorFromAdmissionQuery = mainQuery + $@" and pr2.""ProviderId"" in (Select distinct ""ProviderId""  from ""Admission"" where ""PatientId"" = {patientId})";

            var doctorFromAdmission = (await this.unitOfWork.Current.QueryAsync<Resource>(doctorFromAdmissionQuery)).ToList();

            var doctorFromAppointmentQuerry = mainQuery + $@" and pr2.""ProviderId"" in (Select distinct ""ProviderId""  from ""Appointment"" where ""PatientId"" = {patientId})";

            var doctorFromAppointment = (await this.unitOfWork.Current.QueryAsync<Resource>(doctorFromAppointmentQuerry)).ToList();

            var singleDoctorList = new List<Resource>();
            if (doctorFromAdmission.Count > 0)
            {
                singleDoctorList.AddRange(doctorFromAdmission);
            }
            if (doctorFromAppointment.Count > 0)
            {
                foreach (var item in doctorFromAppointment)
                {
                    var finded = (singleDoctorList.Where(m => m.Id == item.Id)).ToList();
                    if (finded.Count > 0)
                    {
                        continue;
                    }
                    else
                    {
                        singleDoctorList.Add(item);
                    }
                }
            }

            return singleDoctorList.Distinct().ToList();
        }

        /// <inheritdoc />
        public async Task<List<Resource>> FetchPatientAppointmentDoctorsOnlyAsync(int patientId, int locationId)
        {
            var query = $@"SELECT DISTINCT pr2.""FullName"" as ""Value"" ,pr2.""ProviderId"" AS ""Id"",a.""SpecializationId""::text as ""OptionalText""
                           from ""Provider"" pr2
                           join ""Appointment"" a on a.""ProviderId"" = pr2.""ProviderId""
                           where a.""PatientId"" = {patientId} and a.""AppointmentDate""::date = '{(DateTime.UtcNow.AddMinutes(330)).ToString("yyyy-MM-dd")}' and a.""LocationId"" = {locationId}";

            var doctorFromAppointment = (await this.unitOfWork.Current.QueryAsync<Resource>(query)).ToList();

            var singleDoctorList = new List<Resource>();
            if (doctorFromAppointment.Count > 0)
            {
                singleDoctorList.AddRange(doctorFromAppointment);
            }

            return singleDoctorList.Distinct().ToList();
        }

        /// <inheritdoc />
        public async Task<List<Resource>> FetchPatientAdmissionDoctorsOnlyAsync(int patientId, int locationId)
        {
            var mainQuery = $@"SELECT DISTINCT pr2.""FullName"" as ""Value"", d.""DepartmentName"" AS ""OptionalText"", d.""DepartmentId"" AS ""OptionalId"",pr2.""ProviderId"" AS ""Id"",(CASE WHEN pr2.""ThumbnailUrl"" IS NOT NULL THEN CONCAT('{this.amazonS3Configuration.BucketURL}', pr2.""Guid"", '/', pr2.""ThumbnailUrl"") ELSE NULL END) AS ""OptionalText2""
                           FROM ""ProviderLocation"" prl
                           JOIN ""Location"" pral on pral.""LocationId"" = prl.""LocationId"" AND pral.""Active"" IS TRUE
                           JOIN ""Practice"" pra on pra.""PracticeId"" = pral.""PracticeId"" AND pra.""Active"" IS TRUE
                           JOIN ""Provider"" pr2 on pr2.""ProviderId"" = prl.""ProviderId""
                            JOIN ""Department"" d on d.""DepartmentId"" = pr2.""DepartmentId""  WHERE pr2.""Active"" = true ";

            var doctorFromAdmissionQuery = mainQuery + $@" and pr2.""ProviderId"" in (Select distinct ""ProviderId""  from ""Admission"" ad
							LEFT join ""Discharge"" ds on ds.""AdmissionId"" = ad.""AdmissionId""  where ""PatientId"" = {patientId}
                            AND ds.""DischargeId"" IS NULL AND ad.""Active"" IS TRUE)";

            var doctorFromAdmission = (await this.unitOfWork.Current.QueryAsync<Resource>(doctorFromAdmissionQuery)).ToList();



            var singleDoctorList = new List<Resource>();
            if (doctorFromAdmission.Count > 0)
            {
                singleDoctorList.AddRange(doctorFromAdmission);
            }

            return singleDoctorList.Distinct().ToList();
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> PharmacyLogTypesAsync()
        {
            var where = $@" WHERE ""Active"" IS TRUE";
            var query = $@"SELECT ""PharmacyLogTypeId"" AS ""Id"", ""LogTypeName"" AS ""Value"" FROM ""PharmacyLogType"" {where} ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        public Task<IEnumerable<Resource>> InventoryLogTypesAsync()
        {
            var where = $@" WHERE ""Active"" IS TRUE";
            var query = $@"SELECT ""InventoryLogTypeId"" AS ""Id"", ""LogTypeName"" AS ""Value"" FROM ""InventoryLogType"" {where} ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        /// <inheritdoc />
        public Task<IEnumerable<Resource>> LabLogTypesAsync()
        {
            var where = $@" WHERE ""Active"" IS TRUE";
            var query = $@"SELECT ""LabLogTypeId"" AS ""Id"", ""LogTypeName"" AS ""Value"" FROM ""LabLogType"" {where} ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> ScanLogTypesAsync()
        {
            var where = $@" WHERE ""Active"" IS TRUE";
            var query = $@"SELECT ""ScanLogTypeId"" AS ""Id"", ""LogTypeName"" AS ""Value"" FROM ""ScanLogType"" {where} ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        /// <inheritdoc />
        public Task<IEnumerable<Resource>> FetchDischargeStatusAsync()
        {
            var query = $@"SELECT DISTINCT ""DischargeStatus"" as ""Value"",""DischargeStatusId"" as ""Id"" FROM ""DischargeStatus"" ";

            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        /// <inheritdoc />
        public Task<IEnumerable<Resource>> FetchLabNames()
        {
            var query = $@"SELECT ""LabName"" as ""Value"",""LabHeaderId"" as ""Id"" from ""LabHeader""";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        /// <inheritdoc />FetchProvidersAsync
        public Task<IEnumerable<Resource>> FetchProviderAsync(int? locationId, int providerId)
        {
            var where = $@"where 1=1 and pr2.""Active"" is true ";
            if (locationId != null)
            {
                where += $@" and prl.""LocationId"" = {locationId}";
            }

            if (providerId != 0)
            {
                where += $@" and pr2.""ProviderId"" = {providerId}";
            }

            var query = $@"SELECT DISTINCT pr2.""ProviderId"" AS ""Id"",pr2.""FullName"" as ""Value"", --prl.""ProviderAvailabilityId"" as ""OptionalData"" ,
                            d.""DepartmentName""  AS ""OptionalText"" , d.""DepartmentId"" AS ""OptionalId"",  prl.""LocationId"" AS ""OptionalId"",
                            (CASE WHEN pr2.""ThumbnailUrl"" IS NOT NULL THEN CONCAT('{this.amazonS3Configuration.BucketURL}', pr2.""Guid"", '/', pr2.""ThumbnailUrl"") ELSE NULL END) AS ""OptionalText2""
                            from ""Provider"" pr2
                            join ""ProviderAvailability"" prl on   prl.""ProviderId"" = pr2.""ProviderId""
                            join ""Specialization"" s on s.""SpecializationId"" = ANY(pr2.""Specializations"") and s.""Active"" = true
                            join ""Location"" l on l.""LocationId"" = prl.""LocationId""
                            JOIN ""Department"" d on d.""DepartmentId"" = pr2.""DepartmentId""
                            JOIN ""Practice"" pra on pra.""PracticeId"" = l.""PracticeId"" AND pra.""Active"" IS TRUE
                               {where}  ORDER BY pr2.""FullName"" ";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> ProviderSchdule(int? locationId)
        {
            var where = $@"where 1=1  ";
            if (locationId != null)
            {
                where += $@" and PAS.""LocationId"" = {locationId}";
            }
            var query = $@"Select distinct p.""FullName"" as ""Value"",
PAS.""ProviderId"" as ""Id""
                                    from ""ProviderAvailabilityChargeType"" PAS
                                     join ""Provider"" p on p.""ProviderId"" = PAS.""ProviderId""
                                        {where} ";


            //    var query = $@"select  DISTINCT PAS.""ProviderId"" as ""Id"",L.""LocationId"",pr2.""FullName"" as ""Value""
            //from	""ProviderAvailabilityChargeType"" PAS
            //	join ""Location"" L on L.""LocationId"" = PAS.""LocationId""
            //	JOIN ""Provider"" pr2 on pr2.""ProviderId"" = PAS.""ProviderId""
            //	   {where}";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        public Task<IEnumerable<Resource>> WidgetTypesAsync()
        {
            //var where = $@" WHERE ""Active"" IS TRUE";
            var query = $@"SELECT ""DashboardWidgetTypeId"" AS ""Id"", ""Name"" AS ""Value"" FROM ""DashboardWidgetType"" ORDER BY 1 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }


        /// <inheritdoc />
        public Task<IEnumerable<Resource>> FetchPayTypeAsync(bool? isSalucro)
        {
            var query = "";
            if (isSalucro == true)
            {
                query = $@"SELECT ""SalucroPayType"" as ""IsSalucro"", ""PayTypeId"" as ""Id"", ""PayTypeName"" as ""Name"",""PayTypeValue"" as ""Value"" FROM ""PayType"" WHERE ""IsActive""='true' AND ""SalucroPayType""=true order by ""PayTypeId""";
            }
            else
            {
                query = $@"SELECT ""SalucroPayType"" as ""IsSalucro"",""PayTypeId"" as ""Id"", ""PayTypeName"" as ""Name"",""PayTypeValue"" as ""Value"" FROM ""PayType"" WHERE ""IsActive""='true' AND ""SalucroPayType""=false order by ""PayTypeId""";
            }
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> FetchAllPayTypesAsync(bool onlyActive)
        {
            var query = $@"SELECT ""PayTypeId"" as ""Id"", ""PayTypeName"" as ""Name"", ""PayTypeValue"" as ""Value"" from ""PayType""";
            if (onlyActive)
            {
                query += $@"WHERE ""IsActive"" IS true";
            }
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> WidgetsAsync(string? searchParam)
        {
            var where = " WHERE 1 = 1 ";

            if (!string.IsNullOrEmpty(searchParam))
            {
                where += $@" AND TRIM(UPPER(d.""Name"")) ILIKE '%{searchParam.Trim().ToUpper()}%' AND d.""Active"" IS TRUE";
            }

            var query = $@"SELECT DISTINCT d.""DashboardWidgetId"" AS ""Id"", d.""Name"" AS ""Value"" FROM ""DashboardWidget"" d {where} ORDER BY 2 ASC";

            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> StatesAsync(int cId)
        {
            var where = $@" WHERE ""CountryId"" = {cId}";
            var query = $@"SELECT ""StateId"" AS ""Id"", ""StateName"" AS ""Value"" FROM ""State"" {where} ORDER BY 1 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> CitiesAsync(int sId)
        {
            var where = $@" WHERE ""StateId"" = {sId}";
            var query = $@"SELECT ""CityId"" AS ""Id"", ""CityName"" AS ""Value"" FROM ""City"" {where} ORDER BY 1 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> PackageAsync(int id)
        {
            var query = $@"SELECT ""PackageId"" AS ""Id"", ""Name"" AS ""Value"" FROM ""Package"" ORDER BY 1 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> DemandProductsAsync()
        {
            var query = $@"SELECT ""DemandBookId"" AS ""Id"", ""ProductName"" AS ""Value"" FROM ""DemandBook"" ORDER BY 1 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }


        public Task<IEnumerable<Resource>> FetchFloors(int locationId)
        {
            var query = $@"SELECT F.""FloorId"" AS ""Id"",
                        F.""FloorName"" AS ""Value"", L.""Name"" AS ""OptionalText""
                            FROM ""Floor"" F
                            join ""Location"" L on F.""LocationId""=L.""LocationId""
                        Where F.""Active"" = true and F.""LocationId""={locationId} ORDER BY 1 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchAllFloors()
        {
            var query = $@"SELECT ""FloorId"" AS ""Id"",""FloorName"" AS ""Name"", ""LocationId"" AS ""OptionalId"" from ""Floor""";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> FetchWards(int? floorId)
        {
            var where = $@"where 1=1 ";
            if (floorId != null)
            {
                where += $@"And F.""FloorId"" = {floorId}";
            }
            where += $@"And F.""Active"" = true and W.""Active"" = true ORDER BY 1 ASC";
            var query = $@"SELECT ""WardId"" AS ""Id"", ""WardName"" AS ""Value"",F.""FloorName"" as ""OptionalText"",F.""FloorId"" as ""OptionalId""
                        FROM ""Ward"" W
                        left Join ""Floor"" F on F.""FloorId"" = W.""FloorId""
                        {where}";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchAllWards()
        {
            //var query = $@"SELECT ""WardId"" AS ""Id"",""WardName"" AS ""Name"", ""FloorId"" AS ""OptionalId"" from ""Ward""";
            var query = $@"SELECT w.""WardId"" AS ""Id"",w.""WardName"" AS ""Name"", w.""FloorId"" AS ""OptionalId"",f.""LocationId"" as ""OptionalId1"" 
                            from ""Ward"" w
                            left join ""Floor"" f on f.""FloorId"" = w.""FloorId""";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> FetchRooms(int? wardId)
        {
            var where = $@"where 1=1 ";
            if (wardId != null)
            {
                where += $@"And w.""WardId"" = {wardId}";
            }
            where += $@"and r.""Active"" = true ORDER BY 1 ASC";
            var query = $@"SELECT ""RoomId"" AS ""Id"", ""RoomName"" AS ""Value"",w.""WardId"" as ""OptionalId"", w.""WardName"" as ""OptionalText""
                            FROM ""Room"" r
                            left join ""Ward"" w on w.""WardId"" = r.""WardId"" {where}";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchAllRooms(int? locationid)
        {
            var where = $@"where 1=1 ";
            if (locationid != null)
            {
                where += $@"And F.""LocationId"" = {locationid}";
            }
            //var query = $@"SELECT ""RoomId"" AS ""Id"",""RoomName"" AS ""Name"", ""WardId"" AS ""OptionalId"" from ""Room""";
            var query = $@"SELECT r.""RoomId"" AS ""Id"",r.""RoomName"" AS ""Name"", r.""WardId"" AS ""OptionalId"",f.""LocationId"" as ""OptionalId1"" 
						  FROM ""Room"" r
                                         join ""ChargeCategory"" cc on cc.""ChargeCategoryId"" = r.""ChargeCategoryId""
                                         join ""Ward"" w on w.""WardId"" = r.""WardId""
                                         join ""Floor"" F on F.""FloorId"" =w.""FloorId"" 
                                            Join ""Location"" L on L.""LocationId"" =F.""LocationId""
                                         left Join ""Account"" CA ON CA.""AccountId"" = r.""CreatedBy""
                                        Left Join ""Account"" MA ON MA.""AccountId"" = r.""ModifiedBy"" {where}";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> FetchBeds(int? roomId)
        {
            var where = $@"where 1=1 ";
            if (roomId != null)
            {
                where += $@"And r.""RoomId"" = {roomId} ";
            }
            where += $@"And b.""Active"" = true ORDER BY 1 ASC";
            var query = $@"SELECT ""BedId"" AS ""Id"", ""BedNumber"" AS ""Value"", r.""RoomId"" as ""OptionalId"", r.""RoomName"" as ""OptionalText""
                            FROM ""Bed"" b
                             left join ""Room"" r on r.""RoomId"" = b.""RoomId"" {where}";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchAllBeds()
        {
            //var query = $@"SELECT b.""BedId"" AS ""Id"",b.""BedNumber"" AS ""Name"", b.""RoomId"" AS ""OptionalId"", b.""BedStatusId"" AS ""OptionalId1"",bs.""BedStatusName"" AS ""Value"" from ""Bed"" b join ""BedStatus"" bs on bs.""BedStatusId"" = b.""BedStatusId""";
            var query = $@"SELECT b.""BedId"" AS ""Id"",b.""BedNumber"" AS ""Name"", b.""RoomId"" AS ""OptionalId"", b.""BedStatusId"" AS ""OptionalId1"",bs.""BedStatusName"" AS ""Value"",f.""LocationId"" AS ""optionalData"" 
                            FROM ""Bed"" b 
                            JOIN ""BedStatus"" bs ON bs.""BedStatusId"" = b.""BedStatusId""
                            LEFT JOIN ""Room"" r ON r.""RoomId"" = b.""RoomId"" 
                            LEFT JOIN ""Ward"" w ON w.""WardId"" = r.""WardId""
                            LEFT JOIN ""Floor"" f ON f.""FloorId"" = w.""FloorId""";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);

        }
        public Task<IEnumerable<Resource>> FetchBedStatus()
        {
            var query = $@"SELECT ""BedStatusId"" AS ""Id"", ""BedStatusName"" AS ""Name"" FROM ""BedStatus""";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<BedManagementFilterModel>> FetchBedsResource(BedManagementFilterModel model)
        {
            var where = $@"where 1=1";
            if (model.FloorId != null)
            {
                where += $@"and f.""FloorId""={model.FloorId}";
            }
            if (model.LocationId > 0)
            {
                where += $@"and f.""LocationId""={model.LocationId}";
            }
            if (model.WardId != null)
            {
                where += $@"and w.""WardId""={model.WardId}";
            }
            if (model.RoomId != null)
            {
                where += $@"and r.""RoomId""={model.RoomId}";
            }
            if (model.BedId != null)
            {
                where += $@"and b.""BedId""={model.BedId}";
            }
            if (model.BedStatusId != null)
            {
                where += $@"and bs.""BedStatusId""={model.BedStatusId}";
            }
            var query = $@"Select f.""FloorId"",f.""FloorName"",w.""WardId"",w.""WardName"",r.""RoomId"",r.""RoomName"",b.""BedId"",b.""BedNumber"",bs.""BedStatusId"",bs.""BedStatusName"" from ""Floor"" f
                            join ""Ward"" w on w.""FloorId"" = f.""FloorId""
                            join ""Room"" r on r.""WardId"" = w.""WardId""
                            join ""Bed"" b on b.""RoomId"" = r.""RoomId""
                            right join ""BedStatus"" bs on bs.""BedStatusId""  = b.""BedStatusId""
                            {where} and f.""Active""  = true and w.""Active"" = true and r.""Active""=true and b.""Active""=true";
            return this.unitOfWork.Current.QueryAsync<BedManagementFilterModel>(query);
        }

        public Task<IEnumerable<Resource>> FetchImages(int? imageId)
        {
            var where = $@"where 1=1 ";
            //if (imageId != null)
            //{
            //    where += $@"And i.""ImageId"" = {imageId} ";
            //}
            //where += $@"And b.""Active"" = true ORDER BY 1 ASC";
            var query = $@"SELECT ""ImageId"" AS ""Id"", ""ImagePath"" AS ""Value"" FROM ""Image"" ORDER BY 1 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        //public Task<IEnumerable<Resource>> FetchNurses()
        //{
        //    var query = $@"SELECT acc.""AccountId"" AS ""Id"",acc.""FullName"" as ""Value"" From ""Account"" acc
        //                   join ""User"" usr on usr.""UserId"" = acc.""ReferenceId""
        //                   where acc.""RoleId"" = 11";
        //    return this.unitOfWork.Current.QueryAsync<Resource>(query);
        //}

        public Task<IEnumerable<Resource>> FetchShifts()
        {
            var query = $@"Select ""ShiftId"" as ""Id"",""Name"" as ""Value"" from ""Shift"" where ""Active""= true";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> FetchSlots(int shiftId)
        {
            var query = $@"Select ssm.""ShiftSlotMapId"" as ""Id"",(TO_CHAR(""StartTime"", 'HH12:MI AM') || ' - ' || TO_CHAR(""EndTime"", 'HH12:MI AM')) as ""OptionalText"" from ""ShiftSlotMap"" ssm
                            join ""ShiftSlot"" ss on ss.""ShiftSlotId"" = ssm.""ShiftSlotId""
                            where ssm.""ShiftId"" = {shiftId}";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> FetchInsuranceTypes()
        {
            var query = $@"Select ""TypeName"" as ""Value"",""InsuranceTypeId"" as ""Id"" from ""InsuranceType""
                            where ""Active"" = true";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> FetchHowDidYouKnowAsync()
        {
            var query = $@"Select ""Name"" as ""Value"",""HowDidYouKnowId"" as ""Id"" from ""HowDidYouKnow""
                            where ""Active"" = true order by ""HowDidYouKnowId""";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> FetchEducationAsync()
        {
            var query = $@"Select ""Name"" as ""Value"",""EducationId"" as ""Id"" from ""Education""
                            where ""Active"" = true order by ""EducationId""";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> FetchOccupationAsync()
        {
            var query = $@"Select ""Name"" as ""Value"",""OccupationId"" as ""Id"" from ""Occupation""
                            where ""Active"" = true order by ""OccupationId""";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public async Task<IEnumerable<Resource>> FetchPatientInsurances(int patientId)
        {
            var query = $@"Select pi.""PatientInsuranceId"" as ""Id"",it.""TypeName"" as ""OptionalText2"",ic.""FullName"" as ""Value"",pi.""InsuranceCompanyId""::text as ""OptionalText"" from ""InsuranceCompany"" ic
                            join ""PatientInsurance"" pi on ic.""InsuranceCompanyId"" = pi.""InsuranceCompanyId"" and ic.""Active"" is true
                            --join ""Admission"" ad on ad.""PatientId"" = pi.""PatientId""
                            join ""InsuranceType"" it on it.""InsuranceTypeId"" = pi.""InsuranceTypeId""
                            where pi.""PatientId"" = {patientId}";
            var record = await this.unitOfWork.Current.QueryAsync<Resource>(query);
            return record;

        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> FetchRetailStoreAsync(int? locationId)
        {
            var where = $@"where 1=1 and RP.""Active"" is true ";
            if (locationId != null)
            {
                where += $@" and PWH.""LocationId"" = {locationId}";
            }
            var query = $@"SELECT distinct RP.""RetailPharmacyId"" as ""Id"" , RP.""RetailName"" as ""Value"" from ""RetailPharmacy"" RP
                             join ""RetailWareHouseLink"" RWL on RWL.""RetailPharmacyId"" = RP.""RetailPharmacyId""
	                         join ""PharmacyWareHouse"" PWH on PWH.""PharmacyWareHouseId"" = RWL.""PharmacyWareHouseId""
	                         {where}";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> FetchPharmaUsers()
        {
            var query = $@"SELECT ""FullName"" as ""Value"",""Email"" as ""OptionalText2"" from ""User"" where ""RoleId"" in (1,8,15)";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> FetchWareHouseAsync(int? locationId)
        {
            var where = "where 1=1";
            if (locationId != null)
            {
                where += $@" and ""LocationId"" = {locationId}";
            }
            var query = $@"SELECT distinct ""PharmacyWareHouseId"" as ""Id"",""WareHouseName"" as ""Value"" from ""PharmacyWareHouse"" {where}";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> FetchInventoryWareHouseAsync(int? locationId)
        {

            var where = "where 1=1";
            if (locationId != null)
            {
                where += $@" and ""LocationId"" = {locationId}";
            }
            var query = $@"select distinct ""InventoryWareHouseId"" as ""Id"" , ""Name"" as ""Name"" from ""InventoryWareHouse"" {where}";

            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> FetchMealTypeAsync()
        {
            var query = $@"SELECT ""MealType"" as ""Value"",""MealTypeId"" as ""Id"" from ""MealTypes"" ";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> ProviderPracticeLocationAsync(int? locationId)
        {
            var where = $@" WHERE prl.""Active"" = true";
            if (locationId != null)
            {
                where += $@" and prl.""LocationId""={locationId}";
            }

            var query = $@"SELECT prl.""PracticeLocationId"" AS ""Id"", pra.""FullName"" as ""Value"", prl.""FullName"" AS ""OptionalText"", c.""CurrencySymbol"" AS ""OptionalText2"",
                                prl.""StreetAddress"" as ""Name"", prl.""Phone"" as ""OptionalText"", prl.""Email"" as ""OptionalText1""
                                FROM ""PracticeLocation"" prl
                                JOIN ""Country"" c on c.""CountryId"" = prl.""CountryId""
                                JOIN ""Practice"" pra on pra.""PracticeId"" = prl.""PracticeId"" AND pra.""Active"" IS TRUE
                                {where} ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }


        /// <inheritdoc />
        public Task<IEnumerable<Resource>> AdmissionProviderAsync(int? departmentId, int? locationId)
        {
            //var where = $@" WHERE PR.""Active"" = true and PR.""PracticeLocationId"" is not null";
            var where = $@" WHERE 1=1 ";
            if (departmentId != null)
            {
                where += $@" AND pr2.""DepartmentId"" = {departmentId} ";
            }
            if (locationId > 0)
            {
                where += $@" AND prl.""LocationId"" = {locationId} ";
            }
            //var query = $@"select PR.""FullName"" as ""Value"",d.""DepartmentName"" AS ""OptionalText"", PR.""DepartmentId"" AS ""OptionalId"", PR.""ProviderId"" AS ""Id""
            //                                ,(CASE WHEN PR.""ThumbnailUrl"" IS NOT NULL THEN CONCAT('{this.amazonS3Configuration.BucketURL}',
            //                       PR.""Guid"", '/',
            //                       PR.""ThumbnailUrl"") ELSE NULL END) AS ""OptionalText2""
            //                                from ""Provider""	PR
            //                                JOIN ""Department"" d on d.""DepartmentId"" = PR.""DepartmentId""
            //                                JOIN ""LocationDepartmentMap"" LDM on LDM.""DepartmentId"" = d.""DepartmentId""
            //                                {where} ";
            var query = $@"SELECT DISTINCT  prl.""ProviderLocationId"" ,pr2.""FullName"" as ""Value"" , d.""DepartmentName"" as ""OptionalText1"" , d.""DepartmentId"" as ""OptionalId""
,pr2.""ProviderId"" AS ""Id"", s. ""SpecializationId"", s.""SpecializationName"" AS ""OptionalText"" , prl.""LocationId""
                           FROM ""ProviderLocation"" prl
                           JOIN ""Location"" pral on pral.""LocationId"" = prl.""LocationId"" AND pral.""Active"" IS TRUE

                           JOIN ""Practice"" pra on pra.""PracticeId"" = pral.""PracticeId"" AND pra.""Active"" IS TRUE
                           JOIN ""Provider"" pr2 on pr2.""ProviderId"" = prl.""ProviderId"" and pr2.""Active"" is true
						   join ""Specialization"" s on s.""SpecializationId"" = ANY (pr2.""Specializations"")
						   JOIN ""Department"" d on d.""DepartmentId"" = pr2.""DepartmentId""
{where} and s.""Active"" = true";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> FetchProblemsAsync()
        {
            var where = $@" WHERE ""IsActive"" IS TRUE";
            var query = $@"SELECT DISTINCT ""ProblemId"" AS ""Id"", ""Name"" AS ""Value"" ,""Description""  AS ""OptionalText""
                        FROM ""Problem""
                        {where} ORDER BY ""Name"" ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public Task<IEnumerable<Resource>> FetchGoalsAsync(string problemIds)
        {
            var where = @"WHERE ""IsActive"" IS TRUE";
            if (!string.IsNullOrEmpty(problemIds))
            {
                where += $@" AND ""ProblemId"" in ({problemIds})";
            }

            var query = $@"SELECT DISTINCT ""GoalId"" AS ""Id"", ""Name"" AS ""Value"" ,""Description""  AS ""OptionalText""
                        FROM ""Goal""
                        {where} ORDER BY ""Name"" ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public Task<IEnumerable<Resource>> FetchObjectivesAsync(string goalIds)
        {
            var where = @"WHERE ""IsActive"" IS TRUE";
            if (!string.IsNullOrEmpty(goalIds))
            {
                where += $@" AND ""GoalId"" in ({goalIds})";
            }

            var query = $@"SELECT DISTINCT ""ObjectiveId"" AS ""Id"", ""Name"" AS ""Value"" ,""Description""  AS ""OptionalText""
                        FROM ""Objective""
                        {where} ORDER BY ""Name"" ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public Task<IEnumerable<Resource>> FetchInterventionAsync(string objectiveIds)
        {
            var where = @"WHERE ""IsActive"" IS TRUE";
            if (!string.IsNullOrEmpty(objectiveIds))
            {
                where += $@" AND ""ObjectiveId"" in ({objectiveIds})";
            }

            var query = $@"SELECT DISTINCT ""InterventionId"" AS ""Id"", ""Name"" AS ""Value"" ,""Description""  AS ""OptionalText""
                        FROM ""Intervention""
                        {where} ORDER BY ""Name"" ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public Task<IEnumerable<Resource>> FetchLocationsAsync()
        {
            var query = $@"SELECT DISTINCT ""LocationId"" AS ""Id"", ""Name"" AS ""Value""
                        FROM ""Location"" ORDER BY ""Name"" ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public async Task<IEnumerable<Resource>> EmployeeShiftsAsync(int? locationId)
        {
            var response = await this.unitOfWork.EmployeeShifts.FindAllAsync();

            if (locationId != null)
            {
                response.Where(m => m.LocationId == locationId);
            }

            var shifts = response.Where(m => m.Active).Select(m => new Resource
            {
                Id = m.EmployeeShiftId,
                Value = m.EmployeeShiftName,
                OptionalText = DateTime.Today.Add(m.StartTime).ToString("h:mm tt") + " - " + DateTime.Today.Add(m.EndTime).ToString("h:mm tt")
            });

            return shifts.OrderBy(m => m.Value);
        }

        public async Task<IEnumerable<Resource>> FetchHwsMastersAsync(int locationId)
        {
            //var response = await this.unitOfWork.HwcPatients.FindAllAsync(p => p.Active && p.LocationId == locationId);
            //if (response == null)
            //{
            //    return null;
            //}
            //response.Where(m => m.Active).Select(m => new Resource
            //{
            //    Id = m.HWCPatientId,
            //    Value = m.HWCName,
            //    OptionalText = m.Description
            //});

            var query = $@"SELECT ""HWCPatientId"" AS ""Id"",""HWCName"" AS ""value"", ""Description"" AS ""OptionalText"" from ""HWCPatient"" where ""Active"" IS TRUE and ""LocationId"" = {locationId}";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchAllHWCPatients()
        {
            var query = $@"SELECT ""HWCPatientId"" AS ""Id"",""HWCName"" AS ""Name"" from ""HWCPatient""";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> WidgetCountTypesAsync()
        {
            var query = $@"SELECT ""DashboardWidgetCountTypeId"" AS ""Id"", ""Name"" AS ""Value"" FROM ""DashboardWidgetCountType"" ORDER BY 1 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public Task<IEnumerable<Resource>> AppointmentTypeAsync()
        {
            var query = $@"SELECT DISTINCT ""AppointmentTypeId"" AS ""Id"", ""Name"" AS ""Value""
                        FROM ""AppointmentType"" ORDER BY 1 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> ReferredByNamesAsync()
        {
            // PatientReferredById","Name"
            var query = $@"SELECT ""PatientReferredById"" AS ""Id"", ""Name"" AS ""Value"" FROM ""PatientReferredBy"" where ""Active"" is true ";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> ScanMachineAsync(int? locationId)
        {
            var where = $@"1=1";
            if (locationId != null)
            {
                where += @$" and Sa.""LocationId"" = {locationId} ";
            }
            var query = $@"select SA.""ScanMachineAvailabilityId"",SA.""ScanMachineMasterId"" as ""Id"",sm.""DisplayName"" as ""OptionalText"",sm.""MachineName"" as ""Value"",SA.""Active""
                            from ""ScanMachineAvailability"" SA
                            left join ""ScanMachineMaster"" sm on sm.""ScanMachineMasterId"" = SA.""ScanMachineMasterId""
                            where {where}  and SA.""Active"" = true and sm.""Active"" = true
                                order by SA.""CreatedDate"" desc";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> FetchScanMachineMasterAsync(int? locationId)
        {
            var where = $@" where 1=1";
            if (locationId != null)
            {
                where += $@"and st.""LocationId"" = {locationId}";
            }
            var query = $@"Select DISTINCT sm.""ScanMachineMasterId"" as ""Id"", sm.""MachineName"" as ""Name"", sm.""DisplayName"" as ""Value"", sm.""Active"" from ""ScanMachineMaster"" sm
                    left join ""ScanMachineTestMap"" st on st.""ScanMachineMasterId"" = sm.""ScanMachineMasterId""
                    {where} and  sm.""Active"" = true
";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchAllScanMachines()
        {
            var query = $@"SELECT SMM.""ScanMachineMasterId"" AS ""Id"",SMM.""MachineName"" AS ""Name"", SMM.""DisplayName"" As ""Value""
                        from ""ScanMachineMaster"" SMM
                        --left join ""ScanMachineTestMap"" smtm on smtm.""ScanMachineMasterId"" = SMM.""ScanMachineMasterId"" ";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchScanMachineFilterMachines(int? locationId)
        {
            var query = $@"select smm.""ScanMachineMasterId"" AS ""Id"",smm.""MachineName"" AS ""Name"",SMM.""DisplayName"" As ""Value""
                    FROM ""ScanMachineMaster"" SMM
                    join ""ScanMachineTestMap"" smtm on smtm.""ScanMachineMasterId"" = SMM.""ScanMachineMasterId""
                    join ""Location"" ll on ll.""LocationId"" = smtm.""LocationId""
                    join ""ScanTestMaster"" smt on smt.""ScanTestMasterId"" = smtm.""ScanTestMasterId"" and smt.""Active"" IS true
                    left join ""Account"" CA on CA.""AccountId"" = SMM.""CreatedBy""
                    left join ""Account"" CM on CM.""AccountId"" = SMM.""ModifiedBy""
                    where 1=1 AND smtm.""LocationId"" = {locationId} AND SMM.""Active"" = True
                    group by  smm.""ScanMachineMasterId"", smm.""MachineName"", smm.""DisplayName"", CA.""FullName"", CM.""FullName"",smtm.""LocationId"",ll.""NameLoc""
                    order by SMM.""CreatedDate"" desc";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchAllScanTests()
        {
            var query = $@"SELECT ""ScanTestMasterId"" AS ""Id"", ""ScanTestName"" AS ""Name"", ""ScanTestCode"" As ""Value"", ""Active"" AS ""Status"" from ""ScanTestMaster"";";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public async Task<IEnumerable<Resource>> FetchScanMachineFilterTests(int? locationId)
        {
            var query = $@"select distinct smt.""ScanTestMasterId"" AS ""Id"",smt.""ScanTestName""  AS ""Name""
                    FROM ""ScanMachineMaster"" SMM
                    join ""ScanMachineTestMap"" smtm on smtm.""ScanMachineMasterId"" = SMM.""ScanMachineMasterId""
                    join ""Location"" ll on ll.""LocationId"" = smtm.""LocationId""
                    join ""ScanTestMaster"" smt on smt.""ScanTestMasterId"" = smtm.""ScanTestMasterId"" and smt.""Active"" IS true
                    left join ""Account"" CA on CA.""AccountId"" = SMM.""CreatedBy""
                    left join ""Account"" CM on CM.""AccountId"" = SMM.""ModifiedBy""
                    where 1=1 AND smtm.""LocationId"" = {locationId} AND SMM.""Active"" = True
					group by  smm.""ScanMachineMasterId"", smm.""MachineName"", smm.""DisplayName"", CA.""FullName"", CM.""FullName"",smtm.""LocationId"",ll.""NameLoc"",smt.""ScanTestMasterId"",smt.""ScanTestName""";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public async Task<IEnumerable<Resource>> FetchLocationScanTests(int? locationId)
        {
            var where = $@"where 1=1 ";
            if (locationId > 0)
            {
                where += $@" and smtm.""LocationId"" = {locationId}";
            }
            var query = $@"select Distinct(stm.""ScanTestMasterId"") AS ""Id"", stm.""ScanTestName"" AS ""Name"", stm.""ScanTestCode"" as ""Value""
                        from ""ChargeModuleDetails"" cm
                        join ""ScanTestMaster"" stm on stm.""ScanTestMasterId"" = cm.""ReferenceId""
                        join ""ScanMachineTestMap"" smtm ON smtm.""ScanTestMasterId"" = stm.""ScanTestMasterId""
                        join ""ScanMachineMaster"" smm on smm.""ScanMachineMasterId"" = smtm.""ScanMachineMasterId"" and smm.""Active"" is true
                        {where} and stm.""Active"" is true order by stm.""ScanTestName"";";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }


        /// <inheritdoc />
        public async Task<IEnumerable<Resource>> FetchLabDepartmentsAsync()
        {
            var query = $@"select * from ""LabDepartment"" where ""Active"" is true";
            var result = await this.unitOfWork.Current.QueryAsync<LabDepartmentModel>(query);
            return result.Select(l =>

                new Resource
                {
                    Id = l.LabDepartmentId,
                    Value = l.DepartmentName,
                    OptionalText = l.Description
                }
            );
        }

        public async Task<IEnumerable<Resource>> FindTestAsync(int? scanMachineMasterId, int? locationId)
        {

            var where = $@" where 1=1";

            if (scanMachineMasterId != null)
            {
                where += $@" and sm.""ScanMachineMasterId"" = {scanMachineMasterId}";
            }
            if (locationId != null)
            {
                where += $@" and smt.""LocationId"" = {locationId}";

            }
            var query = $@"select distinct sm.""ScanMachineMasterId"",ll.""ChargeCategoryId"" as ""OptionalId"",ll.""Amount"" as ""OptionalText1"",cc.""ChargeCategoryName"" as ""OptionalText"",sm.""MachineName"",sm.""DisplayName"",smt.""ScanTestMasterId"" as ""Id"",stm.""ScanTestName"" as ""Value"" from ""ScanMachineMaster"" sm
                                    left join ""ScanMachineTestMap"" smt on smt.""ScanMachineMasterId"" = sm.""ScanMachineMasterId""
                                    left join ""ScanTestMaster"" stm on stm.""ScanTestMasterId"" = smt.""ScanTestMasterId""
									left Join ""LocationScanTestMasterMap"" ll on ll.""ScanTestMasterId"" = stm.""ScanTestMasterId""
									left join ""ChargeCategory"" cc on cc.""ChargeCategoryId"" = ll.""ChargeCategoryId"" {where} and stm.""Active"" = true";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);

        }

        public async Task<IEnumerable<Resource>> FetchAccountAsync(int? accountId, int? locationId)
        {

            var where = $@" where 1=1";

            if (accountId != null)
            {
                where += $@" and LAM.""AccountId"" = {accountId}";
            }
            if (locationId != 0)
            {
                where += $@" and LAM.""LocationId"" = {locationId}";

            }
            //var query = $@"select LAM.""LocationId"" as ""Id"", LAM.""AccountId"" as ""OptionalId"", L.""Name"" as ""Name"", A.""UserName"" as ""Value"", A.""Mobile"" as ""OptionalText"", A.""Email"" as ""OptionalText1"" from ""LocationAccountMap"" LAM
            //                join ""Account"" A on A.""AccountId"" = LAM.""AccountId""
            //                join ""Location"" L on L.""LocationId"" = LAM.""LocationId""{where}";

            var query = $@"select LAM.""LocationId"" as ""Id"", LAM.""AccountId"" as ""OptionalId"", L.""Name"" as ""Name"", UPPER(A.""UserName"") as ""Value"", A.""Mobile"" as ""OptionalText"", UPPER(A.""Email"") as ""OptionalText1"" from ""LocationAccountMap"" LAM
                            join ""Account"" A on A.""AccountId"" = LAM.""AccountId""
                            join ""Location"" L on L.""LocationId"" = LAM.""LocationId"" {where} order by L.""Name"" asc";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);

        }

        public async Task<IEnumerable<Resource>> FetchAccountDynamicAsync(string type, string value, int? locationId)
        {
            var where = $@" where 1=1";

            if (locationId != 0)
            {
                where += $@" and LAM.""LocationId"" = {locationId}";
            }

            if (type == "M")
            {
                where += $@" and LOWER(A.""Mobile"") = LOWER('{value}') ";
            }

            if (type == "E")
            {
                where += $@" and LOWER(A.""Email"") = LOWER('{value}') ";
            }

            if (type == "U")
            {
                where += $@" and LOWER(A.""UserName"") = LOWER('{value}') ";
            }

            var query = $@"select LAM.""LocationId"" as ""Id"", LAM.""AccountId"" as ""OptionalId"", L.""Name"" as ""Name"", UPPER(A.""UserName"") as ""Value"", A.""Mobile"" as ""OptionalText"", UPPER(A.""Email"") as ""OptionalText1"" from ""LocationAccountMap"" LAM
                            join ""Account"" A on A.""AccountId"" = LAM.""AccountId""
                            join ""Location"" L on L.""LocationId"" = LAM.""LocationId"" {where} order by L.""Name"" asc";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public async Task<IEnumerable<Resource>> FetchProviderAccountAsync(int? accountId, int? locationId)
        {

            var where = $@" where 1=1 and a.""Active"" is true";

            if (accountId != null)
            {
                where += $@" and LAM.""AccountId"" = {accountId}";
            }
            if (locationId != 0)
            {
                where += $@" and LAM.""LocationId"" = {locationId}";

            }

            var query = $@"select p.""ProviderId"" as ""Id"",p.""FullName"" as ""Value"", d.""DepartmentName""  AS ""OptionalText"" , d.""DepartmentId"" AS ""OptionalId"",  lam.""LocationId"" AS ""OptionalData"" from ""Provider"" p
                           join ""Account"" a on a.""ReferenceId"" = p.""ProviderId"" and a.""RoleId"" = {(int)Roles.Provider}
                           join ""LocationAccountMap"" lam on lam.""AccountId"" = a.""AccountId""
                           JOIN ""Department"" d on d.""DepartmentId"" = p.""DepartmentId""
                           {where} order by p.""FullName""";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);

        }

        public async Task<IEnumerable<Resource>> FetchScanProviderAccountAsync(int? accountId, int? locationId)
        {
            var where = $@" where 1=1 and a.""Active"" is true";
            if (accountId != null)
            {
                where += $@" and LAM.""AccountId"" = {accountId}";
            }
            if (locationId != 0)
            {
                where += $@" and LAM.""LocationId"" = {locationId}";
            }
            var query = $@"select p.""ProviderId"" as ""Id"",p.""FullName"" as ""Value"", d.""DepartmentName""  AS ""OptionalText"" , d.""DepartmentId"" AS ""OptionalId"",  lam.""LocationId"" AS ""OptionalData"" from ""Provider"" p
                           join ""Account"" a on a.""ReferenceId"" = p.""ProviderId"" and a.""RoleId"" = {(int)Roles.Provider}
                           join ""LocationAccountMap"" lam on lam.""AccountId"" = a.""AccountId""
                           JOIN ""Department"" d on d.""DepartmentId"" = p.""DepartmentId""
                           {where} order by p.""FullName""";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }


        /// <inheritdoc />
        public Task<IEnumerable<Resource>> ActivePatientsAsync(string? searchParam, int? providerId)
        {
            var where = " WHERE 1 = 1 ";

            if (!string.IsNullOrEmpty(searchParam))
            {
                where += $@" AND (TRIM(UPPER(pat.""FullName"")) ILIKE '%{searchParam.Trim().ToUpper()}%' OR pat.""Mobile"" ILIKE '%{searchParam.Trim().ToUpper()}%' OR pat.""UMRNo"" ILIKE '%{searchParam.Trim().ToUpper()}%') AND pat.""Active"" IS TRUE";
            }

            var query = $@"with cts as (
                            select row_number() over(partition by a.""PatientId"" order by  a.""AppointmentId"" desc,
						 a.""AppointmentDate"" desc )""Max"" ,a.""PatientId"",a.""AppointmentId"",a.""ProviderId"",pr.""FullName""
	                    from ""Appointment"" a
                        join  ""Patient"" pat  on  a.""PatientId""	=pat.""PatientId""
								join ""Provider"" pr on a.""ProviderId"" = pr.""ProviderId""
                        where a.""Active""=true
	                        ),
	                        maxapt as (
                        select a.* from ""Appointment"" a
                        join cts on a.""AppointmentId""=cts.""AppointmentId""
                        where ""Max""=1),
                        patDetails as (SELECT DISTINCT pat.""PatientId"" AS ""Id"", pat.""FullName"" AS ""Value"",pat.""Mobile"" as ""OptionalText2"",pat.""UMRNo"" as ""OptionalText1"",pat.""PaymentStatus"" as ""Status"",
                                                        (CASE WHEN pat.""ThumbnailUrl"" IS NOT NULL THEN CONCAT('https://hims-qa.s3.amazonaws.com/', pat.""Guid"", '/', pat.""ThumbnailUrl"") ELSE NULL END) AS ""OptionalText"",apt.""AppointmentDate"" as ""Date"",apt.""AppointmentTime"" as ""Time"",apt.""ProviderId"" as ""OptionalId"",pr.""FullName"" as  ""Name"",
                        (case when (max(apt.""AppointmentDate"")over(partition by apt.""PatientId"")::text ||' ' || max(apt.""AppointmentTime"")over(partition by apt.""PatientId"")::text)::timestamp > now() at time zone 'UTC-5:30' then true else false end)""IsSelected""
                                        FROM ""Patient"" pat
				                        left join maxapt apt on apt.""PatientId"" = pat.""PatientId"" and apt.""Status"" <> 'C' and apt.""Active""=true
										left join ""Provider"" pr on pr.""ProviderId"" = apt.""ProviderId""
                            {where} ORDER BY 2 ASC)
                           select patDetails.""Id"",patDetails.""Value"", patDetails.""OptionalText2"", patDetails.""OptionalText1"", patDetails.""Status"", patDetails.""OptionalText""
                    , patDetails.""Date"", patDetails.""Time"", patDetails.""OptionalId"", patDetails.""Name"",patDetails.""IsSelected"", (select exists(select aptmn.""PatientId"" from ""Appointment"" aptmn join ""Appointment"" aptm on aptm.""PatientId"" =  patDetails.""Id"")) AS ""Exists""
                    from patDetails";

            if (providerId != null)
            {
                where += $@" AND (A.""ProviderId"" = {providerId} OR pat.""CreatedBy"" = (Select ""Account"".""AccountId"" FROM ""Account"" WHERE ""Account"".""ReferenceId"" = {providerId} AND ""Account"".""RoleId"" = {(int)Roles.Provider} AND ""Account"".""Active"" IS TRUE)) ";

                query = $@"SELECT DISTINCT pat.""PatientId"" AS ""Id"", pat.""FullName"" AS ""Value"",pat.""Mobile"" as ""OptionalText2"",pat.""PaymentStatus"" as ""Status"",
                                (CASE WHEN pat.""ThumbnailUrl"" IS NOT NULL THEN CONCAT('{this.amazonS3Configuration.BucketURL}', pat.""Guid"", '/', pat.""ThumbnailUrl"") ELSE NULL END) AS ""OptionalText""
                                FROM ""Patient"" pat
                                LEFT JOIN ""Country"" C on C.""CountryId"" = pat.""CountryId"" AND C.""Active"" IS TRUE
                                LEFT JOIN ""Account"" ACT on ACT.""ReferenceId"" = pat.""PatientId"" AND ACT.""RoleId"" = {(int)Roles.Patient} AND ACT.""Active"" IS TRUE
                                LEFT JOIN ""Appointment"" A on A.""PatientId"" = pat.""PatientId""
                                {where} ORDER BY 2 ASC";
            }

            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> FetchNotificationTypes()
        {
            var where = $@" where 1=1";
            var query = $@"select ""ModulesMasterId"" as ""Id"",""ModuleName"" as ""Value"" from ""ModulesMaster""";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public Task<IEnumerable<Resource>> ProviderSpecializationAsync(int? providerId, int? locationId)
        {
            var where = " WHERE 1= 1 ";
            if (providerId != null)
            {
                where += $@" AND p.""ProviderId"" = {providerId} and s.""Active"" is true";
            }

            if (locationId != null)
            {
                where += $@" AND ls.""LocationId"" = {locationId}";
            }

            var query = $@"select distinct p.""ProviderId"", p.""FullName"", s.""SpecializationId"" as ""Id"", s.""SpecializationName"" as ""Value""
                            from ""Provider"" P
                            join ""Specialization"" s on s.""SpecializationId"" = ANY (p.""Specializations"")
                            left join ""LocationSpecializationMap"" ls on ls.""SpecializationId"" = s.""SpecializationId""
                            {where}";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        public async Task<IEnumerable<Resource>> FetchInventoryProductsAsync(int? categoryId, string searchTerm)
        {
            var where = $@"where 1=1";
            if (categoryId != null)
            {
                where += $@" and ""CategoryId"" ={categoryId}";
            }
            if (string.IsNullOrEmpty(searchTerm))
            {
                where += $@"and ""ProductName"" ILIKE '%{searchTerm}%'  ";
            }
            var query = $@"select distinct ""InventoryProductId"" as ""Id"", ""ProductName"" as ""Value"", ""CategoryId"" as ""OptionalId""
                                 from ""InventoryProduct"" {where} order by ""ProductName""   ";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> FetchPayCategory()
        {
            var where = $@" where 1=1";
            var query = $@"select ""PayCategoryId"" as ""Id"",""PayCategoryName"" as ""Value"" from ""PayCategory""";
            // where ""Active"" IS TRUE
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> FetchConsultationType()
        {
            var where = $@" where 1=1";
            var query = $@"select ""ConsultationTypeId"" as ""Id"",""Name"" as ""Value"" from ""ConsultationType"" where ""Active"" IS TRUE";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> FetchAvailabilityChargeType(int? chargeId, int? providerAvailabilitySlotId)
        {
            var where = $@" where 1=1";

            if (chargeId != null)
            {
                where += $@" and ""ChargeTypesId"" =  {chargeId}";
            }
            if (providerAvailabilitySlotId != null)
            {
                where += $@" and ""ProviderAvailabilitySlotId"" = {providerAvailabilitySlotId}";
            }

            var query = $@"select   ""ProviderAvailabilityChargeTypeId"",   ""ProviderAvailabilitySlotId"" as ""OptionalId""
                        ,  ""ChargeTypesId"" as   ""Id"",  ""Charge"" as   ""Value""
                                from   ""ProviderAvailabilityChargeType""	 {where} and ""Active"" IS TRUE";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> ProviderAvailabilityAsync(int providerId, int? specializationId, int? locationId, int? consultationTypeId, string appointmentDate)
        {
            var where = $@"where 1=1  and prl.""Active"" is true";

            if (providerId != 0)
            {
                where += $@" and prl.""ProviderId"" = {providerId}";
            }
            if (locationId != null)
            {
                where += $@" and prl.""LocationId"" = {locationId} ";
            }
            if (specializationId != null || specializationId != 0)
            {
                where += $@" and prl.""SpecializationId"" = {specializationId} ";
            }
            if (consultationTypeId != null)
            {
                where += $@" and prl.""ConsultationTypeId"" = {consultationTypeId}";
            }
            if (appointmentDate != null && appointmentDate != "undefined")
            {
                where += $@" and prl.""StartDate""::Date <= '{appointmentDate}'::Date and prl.""EndDate""::Date >= '{appointmentDate}'::Date";
            }

            var query = $@"SELECT prl.""ProviderAvailabilityId"" AS ""Id"", pra.""FullName"" as ""Value"", pral.""Name"" AS ""OptionalText""
                                FROM ""ProviderAvailability"" prl
                                JOIN ""Location"" pral on pral.""LocationId"" = prl.""LocationId"" AND pral.""Active"" IS TRUE
                                JOIN ""Practice"" pra on pra.""PracticeId"" = pral.""PracticeId"" AND pra.""Active"" IS TRUE
                                join ""Provider"" p on p.""ProviderId"" = prl.""ProviderId""
                                join ""Specialization"" s on s.""SpecializationId"" = any(p.""Specializations"")
                                {where} ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> PartsOfDayAsync(int providerId, int? specializationId, int? locationId, string? startDate, string? endDate)
        {
            var where = $@" where 1=1 and prl.""Active"" is true";

            if (providerId != null || providerId != 0)
            {
                where += $@" and prl.""ProviderId"" = {providerId}";
            }
            if (locationId != null)
            {
                where += $@" and prl.""LocationId"" = {locationId} ";
            }
            if (specializationId != null || specializationId != 0)
            {
                where += $@" and s.""SpecializationId"" = {specializationId} ";
            }
            if (startDate != null)
            {
                where += $@" and prl.""ConsultationTypeId"" = {startDate}";
            }

            if (endDate != null)
            {
                where += $@" and prl.""ConsultationTypeId"" = {endDate}";
            }

            var query = $@"SELECT prl.""ProviderAvailabilityId"" AS ""Id"", pra.""FullName"" as ""Value"", pral.""Name"" AS ""OptionalText""
                                FROM ""ProviderAvailability"" prl
                                JOIN ""Location"" pral on pral.""LocationId"" = prl.""LocationId"" AND pral.""Active"" IS TRUE
                                JOIN ""Practice"" pra on pra.""PracticeId"" = pral.""PracticeId"" AND pra.""Active"" IS TRUE
                                join ""Provider"" p on p.""ProviderId"" = prl.""ProviderId""
                                join ""Specialization"" s on s.""SpecializationId"" = any(p.""Specializations"")
                                {where} ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> MenuAccessedRolesAsync(string url)
        {
            var where = url;
            var query = $@"select A.""AccountId"" as ""Id"", R.""RoleName"" as ""OptionalText2"",A.""FullName"" as ""Value"" from ""MenuAccess"" MA
                        join ""Role"" R on R.""RoleId""=MA.""RoleId""
                        join ""Account"" A on A.""RoleId""=MA.""RoleId""
                        WHERE ""IsFullAccess"" IS TRUE
                        UNION
                        SELECt DISTINCT A.""AccountId"",R.""RoleName"",A.""FullName"" from ""MenuRelationship"" MR
                        JOIN ""Menu"" m on m.""MenuId"" = MR.""MenuId""
                        join ""Role"" R on R.""RoleId""=MR.""RoleId""
                        join ""Account"" A on A.""RoleId""=MR.""RoleId""
                        WHERE m.""Url"" = '{where}'";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> FetchPatientByFilter(AppointmentFilterModel model)
        {
            var where = "where 1=1 ";

            if (model.FromDate != null && model.ToDate != null)
            {
                where += $@" and A.""AppointmentDate""::date >= '{model.FromDate}'::date and";
                where += $@" A.""AppointmentDate""::date <= '{model.ToDate}'::date";
            }
            else
            {
                where += $@" and A.""AppointmentDate""='{model.Today}'";
            }
            if (model.LocationId != null)
            {
                where += $@" and A.""LocationId""='{model.LocationId}'";
            }

            var query = $@" select distinct P.""PatientId"" AS ""Id"" , P.""FullName"" AS ""Value"" , P.""Mobile"" as ""OptionalText"", P.""UMRNo"" as ""OptionalText1""
                                 --,A.""AppointmentNo"" As ""AppointmentNo""
                                    from ""Appointment"" A
                            JOIN ""Patient"" P ON P.""PatientId"" = A.""PatientId""
                            {where} ";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);

        }
        /// <inheritdoc />
        public Task<IEnumerable<Resource>> FetchReceiptAreaAsync()
        {
            var query = $@"SELECT ""ReceiptAreaTypeId"" as ""Id"", ""Name"" as ""Value""	FROM ""ReceiptAreaType"" order by ""ReceiptAreaTypeId""";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        /// <inheritdoc />
        public Task<IEnumerable<Resource>> FetchReceiptAreaAsyncs()
        {
            var query = $@"SELECT ""ReceiptAreaTypeId"" as ""Id"", ""Name"" as ""Value""	FROM ""ReceiptAreaType""where ""ReceiptAreaTypeId"" in(1,2,3,4,10,8,12,14)   order by ""ReceiptAreaTypeId""";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> ActiveStatusAsync()
        {
            var query = $@"SELECT ""ActiveStatusId"" AS ""Id"", ""Name"" AS ""Value"" FROM ""ActiveStatus"" ORDER BY 1 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> LocationSpecializationsAsync(int? locationId, int providerId)
        {
            var where = $@" WHERE S.""Active"" IS TRUE";
            if (locationId != null)
            {
                where += $@" and ls.""LocationId"" = {locationId}";
            }

            if (providerId != 0)
            {
                where += $@" and pr.""ProviderId""= {providerId}";
            }

            var query = $@"SELECT DISTINCT s.""SpecializationId"" AS ""Id"",ls.""LocationId"" as ""OptionaltextId"", s.""SpecializationName"" AS ""Value"" ,(case when I.""IconName"" is not null then CONCAT
		                    ('{this.amazonS3Configuration.BucketURL}' ,I.""IconName"") else null end )  AS ""OptionalText"" FROM ""Specialization"" S
                             left join ""Icons"" I on I.""IconsId"" = S.""SpecializationIconId""
		                    left join ""LocationSpecializationMap"" ls on ls.""SpecializationId"" = s.""SpecializationId""
                            join ""Provider"" pr on  S.""SpecializationId"" = ANY(pr.""Specializations"") and s.""Active"" = true
		                    {where}  ORDER BY ""Value"" ASC";
            //var query = $@"SELECT ""SpecializationId"" AS ""Id"", ""SpecializationName"" AS ""Value"" ,(case when I.""IconName"" is not null then CONCAT('{this.amazonS3Configuration.BucketURL}' ,I.""IconName"") else null end )  AS ""OptionalText"" FROM ""Specialization"" S
            //                left join ""Icons"" I on I.""IconsId"" = S.""SpecializationIconId"" {where} ORDER BY ""Priority"" ASC,""SpecializationName"" ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> SpecializationsForProviderAcailabilityAsync(int? locationId)
        {
            var where = $@" WHERE PAS.""Active"" IS TRUE";
            if (locationId != null)
            {
                where += $@" and PAS.""LocationId"" = {locationId}";
            }

            var query = $@"Select distinct sp.""SpecializationName"" as ""Value"",
PAS.""SpecializationId"" as ""Id""
                                    from ""ProviderAvailabilityChargeType"" PAS
                                     join ""Specialization"" sp on sp.""SpecializationId""=PAS.""SpecializationId""
                                        {where} ";

            //var query = $@"SELECT ""SpecializationId"" AS ""Id"", ""SpecializationName"" AS ""Value"" ,(case when I.""IconName"" is not null then CONCAT('{this.amazonS3Configuration.BucketURL}' ,I.""IconName"") else null end )  AS ""OptionalText"" FROM ""Specialization"" S
            //                left join ""Icons"" I on I.""IconsId"" = S.""SpecializationIconId"" {where} ORDER BY ""Priority"" ASC,""SpecializationName"" ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public async Task<IEnumerable<Resource>> FetchPathologyProviders(int? locationId)
        {
            //var where = $@" WHERE pr2.""Active"" = true";

            //if (locationId != null)
            //{
            //    where += $@" and prl.""LocationId""= {locationId}";
            //}

            //var query = $@"SELECT DISTINCT  on (pr2.""ProviderId"", s.""SpecializationId"") prl.""ProviderAvailabilityId"" ,pr2.""FullName"" as ""Value""
            //, d.""DepartmentName"" AS ""OptionalText"" , d.""DepartmentId"" AS ""OptionalId""
            //,pr2.""ProviderId"" AS ""Id""
            //, s. ""SpecializationId""  AS ""OptionalData"", s.""SpecializationName"" AS ""OptionalText1""
            //, prl.""LocationId"", prl.""ConsultationTypeId""
            //                           FROM ""ProviderAvailability"" prl
            //                           JOIN ""Provider"" pr2 on pr2.""ProviderId"" = prl.""ProviderId"" and pr2.""Active"" is true
            //						   join ""Specialization"" s on s.""SpecializationId"" = ANY (pr2.""Specializations"")
            //                           JOIN ""Location"" pral on pral.""LocationId"" = prl.""LocationId"" AND pral.""Active"" IS TRUE
            //                           JOIN ""Practice"" pra on pra.""PracticeId"" = pral.""PracticeId"" AND pra.""Active"" IS TRUE
            //						   JOIN ""Department"" d on d.""DepartmentId"" = pr2.""DepartmentId""
            //						   {where} and s.""Active"" = true
            //						 ORDER BY pr2.""ProviderId"" ";
            //return this.unitOfWork.Current.QueryAsync<Resource>(query);
            var where = $@" where 1=1 and p.""Active"" is true  and d.""DepartmentName"" = 'Pathology'";

            if (locationId != 0)
            {
                where += $@" and lam.""LocationId"" = {locationId}";

            }

            var query = $@"select p.""ProviderId"" as ""Id"",p.""FullName"" as ""Value"", d.""DepartmentName""  AS ""OptionalText"" , d.""DepartmentId"" AS ""OptionalId"",  lam.""LocationId"" AS ""OptionalData"" from ""Provider"" p
                           join ""Account"" a on a.""ReferenceId"" = p.""ProviderId"" and a.""RoleId"" = 3
                           join ""LocationAccountMap"" lam on lam.""AccountId"" = a.""AccountId""
                           JOIN ""Department"" d on d.""DepartmentId"" = p.""DepartmentId""
                           {where} order by p.""FullName""";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);


        }


        /// <inheritdoc />
        public async Task<IEnumerable<Resource>> EncounterTypeAsync()
        {
            var query = $@"SELECT
	                        ""EncounterTypeId"" ""Id"",
	                        ""EncounterName"" ""Name""
                        FROM
	                        ""EncounterType"" order by ""Name"" asc";

            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public async Task<IEnumerable<Resource>> FetchLocationScanTestAsync(int? locationId, int? scanMachineMasterId)
        {
            var where = $@"where 1=1 ";
            if (locationId > 0)
            {
                where += $@" and SMTM.""LocationId"" = {locationId}";
            }
            if (scanMachineMasterId > 0)
            {
                where += $@" and SMTM.""ScanMachineMasterId"" = {scanMachineMasterId} and STM.""Active"" is true";
            }
            //      var query = $@"	  select SMTM.""ScanMachineTestMapId"" as ""OptionalId"" ,  SMTM.""ScanTestMasterId""  as ""Id"", SMTM.""LocationId"", L.""Name"" as ""OptionalText"",STM.""ScanTestName"" as ""Name"" , STM.""ScanTestCode"" as ""Value"", SMTM.""ScanMachineMasterId"" as ""optionalData"", stm.""Duration""
            //from ""ScanMachineTestMap"" SMTM
            //left join ""ScanTestMaster"" STM on STM.""ScanTestMasterId"" = SMTM.""ScanTestMasterId"" and STM.""Active"" is true
            //left join ""Location"" L on L.""LocationId"" = SMTM.""LocationId"" and L.""Active"" is true
            //                         {where} ";
            var query = $@"select Distinct(SMTM.""ScanMachineTestMapId"") as ""OptionalId"", SMTM.""ScanTestMasterId"" as ""Id"", SMTM.""LocationId"", L.""Name"" as ""OptionalText"",STM.""ScanTestName"" as ""Name"" , STM.""ScanTestCode"" as ""Value"", SMTM.""ScanMachineMasterId"" as ""optionalData"", stm.""Duration""
					 from ""ChargeModuleDetails"" cm
					 left join ""ScanMachineTestMap"" SMTM on SMTM.""ScanTestMasterId"" = cm.""ReferenceId""
					 left join ""ScanTestMaster"" STM on STM.""ScanTestMasterId"" = SMTM.""ScanTestMasterId"" and STM.""Active"" is true
					 left join ""Location"" L on L.""LocationId"" = SMTM.""LocationId"" and L.""Active"" is true
                               {where} ";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public async Task<IEnumerable<Resource>> FetchLocationScanMachineAsync(int? locationId)
        {
            var where = $@"where 1=1 ";
            if (locationId != null)
            {
                where += $@" and SMTM.""LocationId"" = {locationId}";
            }
            var query = $@"select Distinct on (SMTM.""ScanMachineMasterId"") SMTM.""ScanMachineTestMapId"" as ""OptionalId"" ,  SMTM.""ScanMachineMasterId""  as ""Id"", SMTM.""LocationId"", L.""Name"" as ""OptionalText"",SMM.""MachineName"" as ""Name"" , SMM.""DisplayName"" as ""Value"",
                     array_to_string(array(select distinct ""ScanTestMasterId"" from ""ScanMachineTestMap"" where ""ScanMachineMasterId"" in (SMTM.""ScanMachineMasterId"")), ',') as ""OptionalText1""
					 from ""ScanMachineTestMap"" SMTM
					 join ""ScanMachineMaster"" SMM on SMM.""ScanMachineMasterId"" = SMTM.""ScanMachineMasterId"" and SMM.""Active"" is true
					 join ""Location"" L on L.""LocationId"" = SMTM.""LocationId"" and L.""Active"" is true
                               {where} ";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public async Task<IEnumerable<Resource>> FetchScanMachinesTestsAsync(string? ScanTestMasterId, string? scanMachineMasterId)
        {

            var where = $@" where 1=1";
            if (scanMachineMasterId != null)
            {
                where += $@" and sm.""ScanMachineMasterId"" in ({scanMachineMasterId})";
            }
            if (ScanTestMasterId != null)
            {
                //where += $@" and smt.""ScanTestMasterId"" in ({scanMachineMasterId})";
                where += $@" and smt.""ScanTestMasterId"" = {ScanTestMasterId}";
            }
            var query = $@"select distinct sm.""ScanMachineMasterId"" as ""Id"",ll.""ChargeCategoryId"" as ""OptionalId"",ll.""Amount"" as ""OptionalText1"", stm.""Duration""
                            , cc.""ChargeCategoryName"" as ""OptionalText"",sm.""MachineName"" as ""Name"",sm.""DisplayName"" as ""Value"",smt.""ScanTestMasterId"" as ""OptionalData""
                            ,stm.""ScanTestName"" as ""OptionalText2"" , ll.""LocationId"" as ""OptionalId1"",
							array_to_string(array(select distinct ""ScanTestMasterId"" from ""ScanMachineTestMap"" where ""ScanMachineMasterId"" in (sm.""ScanMachineMasterId"")), ',') as ""OptionalText3""
                                    from ""ScanMachineMaster"" sm
                                    left join ""ScanMachineTestMap"" smt on smt.""ScanMachineMasterId"" = sm.""ScanMachineMasterId"" and sm.""Active"" is true
                                    left join ""ScanTestMaster"" stm on stm.""ScanTestMasterId"" = smt.""ScanTestMasterId""
									left Join ""LocationScanTestMasterMap"" ll on ll.""ScanTestMasterId"" = stm.""ScanTestMasterId""
									left join ""ChargeCategory"" cc on cc.""ChargeCategoryId"" = ll.""ChargeCategoryId"" {where} and stm.""Active"" = true";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);

        }

        public Task<IEnumerable<Resource>> FetchScanClassification(int? locationId)
        {
            var query = $@"select ""ScanClassificationId"" AS ""Id"", ""ScanClassificationName"" AS ""Name"", ""Active"" as status from ""ScanClassification""";
            if (locationId > 0)
            {
                query = $@"select distinct stm.""ScanClassificationId"" AS ""Id"",sc.""ScanClassificationName"" AS ""Name"" from ""ScanTestMaster"" stm
                    join ""LocationScanTestMasterMap"" lst on lst.""ScanTestMasterId"" = stm.""ScanTestMasterId""
                    join ""ScanClassification"" sc on sc.""ScanClassificationId"" = stm.""ScanClassificationId""
                    where lst.""LocationId"" = {locationId}";
            }
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> FetchSubClassificationTests(int? locationId, int? classificationId, int? subClassificationId)
        {
            var where = $@" where 1=1";
            if (locationId > 0)
            {
                where += $@" and smtm.""LocationId"" = {locationId}";
            }
            if (classificationId > 0)
            {
                where += $@" and stm.""ScanClassificationId"" = {classificationId}";
            }
            if (subClassificationId > 0)
            {
                where += $@" and stm.""ScanSubClassificationId"" = {subClassificationId}";
            }

            var query = $@"select Distinct(stm.""ScanTestMasterId"") AS ""Id"", stm.""ScanTestName"" AS ""Name""
                            from ""ChargeModuleDetails"" cm
                            join ""ScanTestMaster"" stm on stm.""ScanTestMasterId"" = cm.""ReferenceId""
                            join ""ScanMachineTestMap"" smtm on smtm.""ScanTestMasterId"" = stm.""ScanTestMasterId""
                            join ""ScanMachineMaster"" smm on smm.""ScanMachineMasterId"" = smtm.""ScanMachineMasterId"" and smm.""Active"" is true
                            {where}";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> FetchScanSubClassification(int? classificationId)
        {
            var query = $@"select ""ScanSubClassificationId"" AS ""Id"", ""ScanSubClassificationName"" AS ""Name"" from ""ScanSubClassification""";
            if (classificationId > 0)
            {
                //query = $@"select distinct ssc.""ScanSubClassificationId"" AS ""Id"",ssc.""ScanSubClassificationName"" AS ""Name"" from ""ScanSubClassification"" ssc
                // join ""ScanTestMaster"" stm on (stm.""ScanClassificationId"" = ssc.""ScanClassificationId"" and stm.""Active"" is true)
                // left join ""LocationScanTestMasterMap"" lst on lst.""ScanTestMasterId"" =  stm.""ScanTestMasterId""
                //    where stm.""ScanClassificationId"" = {classificationId}";
                query = $@"select ""ScanSubClassificationId"" AS ""Id"", ""ScanSubClassificationName"" AS ""Name"" from ""ScanSubClassification"" where ""Active"" IS true AND ""ScanClassificationId"" = {classificationId}";
            }

            //var where = $@" where 1=1";
            //if (classificationId > 0)
            //{
            //    where += $@" and ""ScanClassificationId"" = {classificationId}";
            //}
            //var query = $@"select ""ScanSubClassificationId"" AS ""Id"", ""ScanSubClassificationName"" AS ""Name"" from ""ScanSubClassification"" AND ""Active"" IS true {where}";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public async Task<IEnumerable<Resource>> FetchScanTestCategoryTypesAsync(int? scanTestMasterId, int? locationId)
        {

            var where = $@" where 1=1";

            if (scanTestMasterId != null)
            {
                where += $@" and cmd.""ReferenceId""  in ({scanTestMasterId})";
            }

            if (locationId != null)
            {
                where += $@" and cmd.""LocationId""  in ({locationId})";
            }
            var query = $@"SELECT cmd.""ChargeModuleDetailsId"", cmd.""ReferenceId"" as ""OptionalId"", cmd.""ChargeModuleCategoryId"", cmd.""Amount"" as ""Cost"", cmd.""LocationId"", cmd.""CreatedBy"", cmd.""CreatedDate"", cmd.""ModifiedBy"", cmd.""ModifiedDate"",
		                            cc.""ChargeCategoryName"" as ""Name"" , cc.""Default"" as ""Status"",cmc.""ChargeCategoryId"" as ""Id"", cmc.""ModulesMasterId"" , cmc.""ChargeModuleTemplateId"",
		                            mm.""ModuleName""
	                            FROM ""ChargeModuleDetails"" cmd
	                            join ""ChargeModuleCategory"" cmc on cmc.""ChargeModuleCategoryId"" = cmd.""ChargeModuleCategoryId""
	                            join ""ChargeCategory"" cc on cc.""ChargeCategoryId"" = cmc.""ChargeCategoryId""
                                and cmc.""ModulesMasterId"" = (select ""ModulesMasterId"" from ""ModulesMaster"" where ""ModuleName"" = 'Scan')
                                and cmc.""ChargeModuleTemplateId"" = (select ""ChargeModuleTemplateId"" from ""ChargeModuleTemplate"" where ""IsInUse"" = true and ""Active"" IS true and ""LocationId"" = {locationId})
	                            join ""ModulesMaster"" mm on mm.""ModulesMasterId"" = cmc.""ModulesMasterId""
                    {where} order by cmd.""ChargeModuleDetailsId"" asc";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);

        }

        public async Task<IEnumerable<Resource>> ChargeCategoryAsync()
        {


            var query = $@"SELECT   ""ChargeCategoryId"" as ""Id"", ""ChargeCategoryName"" as ""Name""
				 FROM ""ChargeCategory""
				where  ""Active"" = true";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);

        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> LocationsForPracticeAsync(int practiceId)
        {

            var where = $@" WHERE 1=1";
            if (practiceId != null && practiceId != 0)
            {
                where += $@" and ""PracticeId"" = {practiceId} ";
            }
            var query = $@"SELECT
	                        ""LocationId"" ""Id"",
	                        ""Name"" ""Name""
                        FROM
	                        ""Location""

            {where}order by ""Name""";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> FetchLocationsForPracticeAsync(int? providerId)
        {

            var where = $@" WHERE 1=1 and prl.""Active"" = true and prl.""CountryId"" = '1'";
            if (providerId != null && providerId != 0)
            {
                where += $@" and P.""ProviderId"" = {providerId} ";
            }
            var query = $@" select distinct prl.""LocationId"" AS ""Id"", pra.""FullName"" as ""Value"", prl.""Name"" AS ""OptionalText"", c.""CurrencySymbol"" AS ""OptionalText2""
from ""Location"" prl
 left JOIN ""Practice"" pra on pra.""PracticeId"" = prl.""PracticeId"" AND pra.""Active"" IS TRUE
 left JOIN ""Country"" c on c.""CountryId"" = prl.""CountryId""
                           left  join ""ProviderAvailability"" P on P.""LocationId"" = prl.""LocationId""

            {where}order by 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }


        public Task<IEnumerable<Resource>> FetchScanAvailabilityStatus()
        {
            var where = $@" WHERE 1=1 and ";

            var query = $@"SELECT LV.""LookupValueId"" as ""Id"", LV.""Name"" as ""Value"", LV.""LookupId"" as ""OptionalId"",  L.""Name"" as ""Name"", LV.""RowColor"" as ""OptionalText""
	                                FROM ""LookupValue"" LV
 	                                JOIN ""Lookup"" L on L.""LookupId"" = LV.""LookupId""
	                                {where} L.""Name"" = 'ScanAvailabilityBreak'";

            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }


        public Task<IEnumerable<Resource>> FetchScanAvailabilityReason()
        {
            var where = $@" WHERE 1=1 and ";

            var query = $@"SELECT LV.""LookupValueId"" as ""Id"", LV.""Name"" as ""Value"", LV.""LookupId"" as ""OptionalId"",  L.""Name"" as ""Name"", LV.""RowColor"" as ""OptionalText""
	                                FROM ""LookupValue"" LV
 	                                JOIN ""Lookup"" L on L.""LookupId"" = LV.""LookupId""
	                                {where} L.""Name"" = 'ScanAvailabilityBlock'";

            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        public Task<IEnumerable<Resource>> FetchScanScrollResult()
        {
            var where = $@" WHERE 1=1 and ";

            var query = $@"SELECT LV.""LookupValueId"" as ""Id"", LV.""Name""
	                                FROM ""LookupValue"" LV
 	                                JOIN ""Lookup"" L on L.""LookupId"" = LV.""LookupId""
	                                {where} L.""Name"" = 'ScanScrollResult'";

            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        public Task<IEnumerable<Resource>> FetchLocationChargeCategoryAsync(int? locationId)
        {
            var where = $@" WHERE 1=1 and c.""Active"" = true";
            //if (locationId != null && locationId != 0)
            //{
            //    where += $@" and RC.""LocationId"" = {locationId} ";
            //}
            var query = $@"select distinct c.""ChargeCategoryId"" as ""Id"",c.""ChargeCategoryName"" as ""Value""
from ""ChargeCategory"" c {where}";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        public Task<IEnumerable<Resource>> FetchCaseTypes()
        {
            var where = $@"where 1=1 and c.""Active"" = true";
            var query = $@"select distinct c.""CaseTypeId"" as ""Id"",c.""CaseTypeName"" as ""Value""
from ""CaseType"" c {where}";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        public Task<IEnumerable<Resource>> FetchEmergencyCaseTypes()
        {
            var where = $@"where 1=1 and c.""IsActive"" = true";
            var query = $@"select distinct c.""emergencyId"" as ""Id"",c.""emergencyName"" as ""Value""
                        from ""EmergencyType"" c {where}";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> FetchOTRoomAsync(int? locationId)
        {
            var where = $@" where 1=1 and otr.""Active""=true";
            if (locationId != null)
            {
                where += $@" and f.""LocationId"" = {locationId}";
            }
            var query = $@"select otr.""OTRoomId"" as id,otr.""RoomName"" as ""Name"",w.""WardName"",f.""LocationId""
	            from ""OTRoom"" otr
	            left join ""Ward"" w on w.""WardId""=otr.""WardId""
	            left join ""Floor"" f on f.""FloorId""=w.""FloorId""
                    {where}";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> SurgeryNamesAsync()
        {
            var query = $@"SELECT DISTINCT ""Name"" as ""Value"",""SurgeryId"" as ""Id"" FROM ""Surgery"" ";

            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        public Task<IEnumerable<Resource>> FetchProvidersForOTAsync(int? locationId)
        {
            var query = $@"SELECT DISTINCT ""FullName"" as ""Value"",""ProviderId"" as ""Id"" FROM ""Provider"" where ""Active""=true";

            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchUsersAllAsync(int roleId, int? location)
        {
            var where = " where 1=1";
            if (roleId > 0)
            {
                where += @$" and rol.""RoleId"" = {roleId}";
            }
            if (location > 0)
            {
                where += $@" and LAM.""LocationId""={location}";
            }
            //            var query = $@"SELECT DISTINCT LAM.""AccountId"" as ""Id"",rol.""RoleName"" as ""OptionalText2"",acc.""FullName"" as ""Value""
            //from ""Account"" acc
            //join ""Role"" rol on acc.""RoleId"" = rol.""RoleId""
            //join ""LocationAccountMap"" LAM on LAM.""AccountId""=acc.""AccountId""

            var qry = $@"SELECT DISTINCT LAM.""AccountId"" as ""Id"",rol.""RoleName"" as ""OptionalText2"",acc.""FullName"" as ""Value""
from ""User"" usr
join ""Role"" rol on usr.""RoleId"" = rol.""RoleId""
join ""Account"" acc on acc.""ReferenceId"" = usr.""UserId""
join ""LocationAccountMap"" LAM on LAM.""AccountId"" = acc.""AccountId""
{where}";
            return await this.unitOfWork.Current.QueryAsync<Resource>(qry);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchAnaesthesiaTypesAsync()
        {
            var query = $@"SELECT  ""AnaesthesiaTypeId"" as Id, ""Name"" as ""Value"" from ""AnaesthesiaType""";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchIdProofsAsync()
        {
            var query = $@"SELECT ""IdProofId"" as Id, ""IdProofName"" as ""Value"" from ""IdProof""";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchSessionTypesAsync()
        {
            var query = $@"SELECT ""SessionTypeId"" as ""Id"", ""Name"" from ""SessionType""";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public async Task<IEnumerable<Resource>> FetchRoomsAsync()
        {
            var query = $@"SELECT ""RoomId"" as ""Id"",""RoomName"" as ""Value"" from ""Room""";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        public Task<IEnumerable<Resource>> FetchPatientNameMobileAsync(string filter, int locationId, string fromDate, string toDate, string toDay)
        {

            var parameters = !string.IsNullOrEmpty(filter) ? $@"'{filter}'" : "null";

            parameters += locationId > 0 ? $@",{locationId}" : ",null";

            //parameters += !string.IsNullOrEmpty(fromDate) ? $@",'{fromDate}'" : ",null";

            //parameters += !string.IsNullOrEmpty(toDate) ? $@",'{toDate}'" : ",null";

            //parameters += !string.IsNullOrEmpty(toDay) ? $@",'{toDay}'" : ",null";

            parameters += fromDate != "null" ? $@",'{fromDate}'" : ",null";

            parameters += toDate != "null" ? $@",'{toDate}'" : ",null";

            parameters += toDay != "null" ? $@",'{toDay}'" : ",null";


            var query = $@"select * from ""udf_FetchPatient_With_Name_Mobile_Umr""({parameters})";

            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }



        public Task<IEnumerable<Resource>> FetchPatientAppointmentAsync(string filter, int locationId, string fromDate, string toDate, string toDay)
        {

            var parameters = !string.IsNullOrEmpty(filter) ? $@"'{filter}'" : "null";

            var location = locationId > 0 ? $@"{locationId}" : "null";



            var fDate = (fromDate != "null" || fromDate != "") ? $@"{fromDate}" : "null";

            var tDate = (toDate != "null" || toDate != "") ? $@"{toDate}" : "null";

            var tDay = (toDay != "null" || toDay != "") ? $@"{toDay}" : "null";
            var query = $@"

        select distinct P.""PatientId"" AS ""Id"" , P.""FullName"" AS ""Value"" ,
         P.""Mobile"" as ""OptionalText"", P.""UMRNo"" as ""OptionalText1"",A.""AppointmentNo"" as ""AppointmentNo""
        from ""Appointment"" A
        JOIN ""Patient"" P ON P.""PatientId"" = A.""PatientId""
        where 1 = 1  and A.""LocationId"" = {location} and LOWER(A.""AppointmentNo"") ilike LOWER('%{filter}%')
	    and case when '{fDate}' is not null and '{tDate}' is not null then A.""AppointmentDate""::date >='{fDate}'::date
        and A.""AppointmentDate""::date <= '{tDate}'::date  else A.""AppointmentDate""::date =
    '{tDay}'::date end limit 50
    ";

            query = query.Replace("\n", " ");
            query = query.Replace("\r", " ");
            Console.WriteLine(query);


            var records = this.unitOfWork.Current.QueryAsync<Resource>(query);
            return records;



        }





        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> FetchsurgerisAsync(int locationId)
        {
            var query = $@"SELECT  ""SurgeryId"" as Id, ""Name"" as ""Value"" from ""Surgery"" where ""LocationId""={locationId} and ""Active""=true";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        public async Task<IEnumerable<Resource>> FetchSurgeryAsync(int? locationId)
        {
            var where = $@"where 1=1 ";
            if ((locationId != null) && (locationId != 0))
            {
                where += $@" and  OTSM.""LocationId"" = {locationId}";
            }
            var qry = $@"   select distinct  OTSM.""SurgeryId"" as ""Id"",S.""Name"" as ""Name"",S.""Duration"" as  ""OptionalText1""
                from ""OTRoomSurgeryMap"" OTSM
                join ""Surgery"" S on S.""SurgeryId"" = OTSM.""SurgeryId"" and S.""Active"" is true {where} ";
            return await this.unitOfWork.Current.QueryAsync<Resource>(qry);
        }
        /// <inheritdoc />
        public async Task<IEnumerable<Resource>> FetchLocationSurgeryAsync(int? locationId)
        {
            var where = $@"where 1=1 ";
            if ((locationId != null) && (locationId != 0))
            {
                where += $@" and  OTSM.""LocationId"" = {locationId}";
            }
            var query = $@"	  select  OTSM.""OTRoomSurgeryMapId"" as ""OptionalId"" ,  OTSM.""SurgeryId""  as ""Id"", OTSM.""LocationId"", L.""Name"" as
""OptionalText"",S.""Name"" as ""Name"" ,S.""Duration""::text as ""OptionalText1"",OTSM.""OTRoomId"" as ""OptionalId1"",OTR.""RoomName"" as ""OptionalText2""
                     from ""OTRoomSurgeryMap"" OTSM
					 join ""Surgery"" S on S.""SurgeryId"" = OTSM.""SurgeryId"" and S.""Active"" is true
                join ""OTRoom"" OTR on OTR.""OTRoomId"" = OTSM.""OTRoomId"" and OTR.""Active"" is true
					 join ""Location"" L on L.""LocationId"" = OTSM.""LocationId"" and L.""Active"" is true
                               {where} ";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        public async Task<IEnumerable<Resource>> FetchUniqueOTRooms(int? locationId)
        {
            var where = $@"where 1=1 and OT.""Active"" is true";
            if ((locationId != null) && (locationId != 0))
            {
                where += $@" and  OTR.""LocationId"" = {locationId}";
            }
            var query = $@" select distinct OTR.""OTRoomId"" as ""OptionalId1"",OT.""RoomName"" as ""OptionalText2"" from ""OTRoomSurgeryMap"" OTR
                                  join ""OTRoom"" OT on OT.""OTRoomId"" = OTR.""OTRoomId""   {where}";
            //var query = $@"	select distinct ""OTRoomId"" as ""OptionalId1"" from ""OTRoomSurgeryMap""";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public async Task<IEnumerable<Resource>> FetchOTRoomSurgeriesAsync(string? surgeryId, string? otRoomId)
        {
            var where = $@" where 1=1";

            if ((surgeryId != null) && (surgeryId != "undefined") && (surgeryId != "0"))
            {
                int s = Convert.ToInt32(surgeryId);
                where += $@" and otm.""SurgeryId"" ={s}";
            }
            if (!string.IsNullOrEmpty(otRoomId) && (otRoomId != "undefined") && (otRoomId != "0"))
            {

                where += $@"  and  otm.""OTRoomId"" in ({otRoomId})";
            }
            var query = $@"select distinct otm.""OTRoomId"" as ""Id"", s.""Duration""
                            ,otr.""RoomName"" as ""Name"",otm.""SurgeryId"" as ""OptionalData""
                            ,s.""Name"" as ""OptionalText2"",SUM(cmd.""Amount"") as ""OptionalText1"",otm.""LocationId"" as ""OptionalId""
                                    from ""OTRoomSurgeryMap"" otm
                                    left join ""OTRoom"" otr on otr.""OTRoomId"" = otm.""OTRoomId""
                                    left join ""Surgery"" s on s.""SurgeryId"" = otm.""SurgeryId""
                                    left join ""ChargeModuleDetails"" cmd on cmd.""ReferenceId"" = otm.""SurgeryId""

                                     {where}
                                    group by otm.""OTRoomId"" , s.""Duration""
                            ,otr.""RoomName"" ,otm.""SurgeryId"",otm.""LocationId""
                            ,s.""Name""";


            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
            //and otr.""Active"" is true
        }


        public async Task<IEnumerable<Resource>> FetchDiscountModule()
        {
            var query = $@"SELECT ""DiscountModuleId"" as Id, ""ModuleName"" as ""Value"" from ""DiscountModule""";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public async Task<IEnumerable<Resource>> FetchAdmissionPayTypes()
        {
            var where = $@"where 1=1 and a.""Active"" = true";
            var query = $@"SELECT a.""AdmissionPayTypeId"" as ""Id"",a.""AdmissionPayTypeName"" as ""Name"" from ""AdmissionPayType"" a {where}";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        /// <summary>
        /// Fetches the patient details.
        /// </summary>
        /// <param name="patientId">The patient identifier.</param>
        /// <returns></returns>
        public async Task<Patient> FetchPatientDetails(int patientId)
        {
            var response = await this.unitOfWork.Patients.FindAsync(d => d.PatientId == patientId);
            return response;
        }

        /// <summary>
        /// Fetches the provider specialization all consulation types.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        public Task<IEnumerable<ProviderSpecializationConsultationtypeModel>> FetchProviderSpecializationAllConsulationTypes(ProviderSpecializationConsultationtypeModel model)
        {
            var where = $@"where 1=1 and  pr.""Active"" is true";
            if (model.LocationId > 0)
            {
                where += $@" and lam.""LocationId"" = {model.LocationId} ";
            }
            //if (!string.IsNullOrEmpty(model.Term))
            //{
            //    where += $@" AND (s.""SpecializationName"" ILIKE '%{model.Term}%' or pr.""FullName"" ILIKE '%{model.Term}%')";
            //}

            if (!string.IsNullOrEmpty(model.SpecializationName))
            {
                where += $@" AND s.""SpecializationName"" ILIKE '%{model.SpecializationName}%' ";
            }
            if (!string.IsNullOrEmpty(model.Term))
            {
                where += $@" AND  pr.""FullName"" ILIKE '%{model.Term}%' ";
            }
            where += $@"order by pr.""ProviderId"")";
            var where2 = $@"where 1=1";
            if (!string.IsNullOrEmpty(model.ConsultationTypeName))
            {
                where2 += $@" AND c.""Name"" ILIKE '%{model.ConsultationTypeName}%' ";
            }
            var query = $@"with cts as(select DISTINCT  on (pr.""ProviderId"", s.""SpecializationId"")  pr.""ProviderId"",pr.""FullName"" as ""DoctorName"",
                           lam.""LocationId"",s.""SpecializationId"",s.""SpecializationName""
                           from ""Provider"" pr
                           join ""Account"" a on a.""ReferenceId"" = pr.""ProviderId"" and a.""RoleId"" = {(int)Roles.Provider}
                           join ""LocationAccountMap"" lam on lam.""AccountId"" = a.""AccountId""
                           join ""Specialization"" s on s.""SpecializationId"" = ANY (pr.""Specializations"")
                           {where}
                           --where pr.""Active"" is true and lam.""LocationId"" = {model.LocationId} order by pr.""ProviderId"" )
                           select count(z.*) over() as ""TotalItems"" , z.*, c.""ConsultationTypeId"",c.""Name"" as ""ConsultationTypeName"" from cts z
                           cross join ""ConsultationType"" c {where2}
                           group by z.*, z.""ProviderId"", z.""SpecializationId"" , z.""DoctorName"",
                           z.""LocationId"",z.""SpecializationId"",z.""SpecializationName"",c.""ConsultationTypeId"",""ConsultationTypeName""";
            if (model.PageIndex != null && model.PageSize != null)
            {
                model.PageIndex = model.PageIndex > 0 ? model.PageIndex - 1 : model.PageIndex;
                query += $@" limit {model.PageSize} offset {model.PageSize * model.PageIndex}";
            }
            return this.unitOfWork.Current.QueryAsync<ProviderSpecializationConsultationtypeModel>(query);
        }


        /// <inheritdoc />
        public async Task<IEnumerable<Resource>> FetchNewPatientAppointmentAsync(int? patientId)
        {
            var where = $@"where 1=1 ";
            if (patientId != null)
            {
                where += $@" and ""PatientId"" = {patientId} and ""Status"" != 'C'";
            }
            var query = $@"	  select ""AppointmentId"" as ""Id"", ""PatientId"" as ""OptionalId"" from ""Appointment""
                               {where} order by 1 desc limit 50";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public async Task<IEnumerable<Resource>> FetchReferralDoctorAsync()
        {
            var where = $@"where 1=1 and ""Active"" = true";
            var query = $@"SELECT ""ReferralDoctorId"" as ""Id"",""FullName"" as ""Name"" from ""ReferralDoctor"" {where} order by 1 desc";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> InPatientsAsync(string? searchParam, int locationId)
        {
            var where = " WHERE 1 = 1 ";
            if (locationId != 0)
            {
                where += $@" and Adm.""LocationId""={locationId}";
            }
            if (!string.IsNullOrEmpty(searchParam))
            {
                where += $@" AND (TRIM(UPPER(pat.""FullName"")) ILIKE '%{searchParam.Trim().ToUpper()}%' OR pat.""Mobile"" ILIKE '%{searchParam.Trim().ToUpper()}%' OR pat.""UMRNo"" ILIKE '%{searchParam.Trim().ToUpper()}%' OR pat.""Email"" ILIKE '%{searchParam.Trim().ToUpper()}%' OR Adm.""AdmissionNo"" ILIKE '%{searchParam.Trim().ToUpper()}%' ) AND pat.""Active"" IS TRUE";
            }
            var query = $@"SELECT DISTINCT Adm.""PatientId"" AS ""Id"",Adm.""AdmissionNo"" AS ""OptionalText3"", pat.""FullName"" AS ""Value"",pat.""Mobile"" as ""OptionalText2"",pat.""UMRNo"" as ""OptionalText1""


                                FROM ""Admission"" Adm
                    left join ""Patient"" pat on pat.""PatientId""=Adm.""PatientId""
            {where} ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> VisitTypesAsync()
        {
            var query = $@"SELECT DISTINCT ""VisitTypeId"" AS ""Id"", ""VisitorName"" AS ""Value""
                        FROM ""VisitType"" ORDER BY 1 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }



        /// <inheritdoc />
        public Task<IEnumerable<Resource>> FetchTpaCompaniesAsync()
        {
            var where = $@" WHERE ""Active"" IS TRUE";
            var query = $@"SELECT ""TpaId"" AS ""Id"", ""Name"" AS ""Value"" FROM ""Tpa"" {where} ORDER BY 1 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public Task<Resource> FetchDefaultChargeCategoryAsync()
        {
            var where = $@" WHERE ""Active"" IS TRUE AND ""Default"" IS TRUE";
            var query = $@"SELECT ""ChargeCategoryId"" AS ""Id"", ""ChargeCategoryName"" AS ""Value"" FROM ""ChargeCategory"" {where}  limit 1";
            return this.unitOfWork.Current.QueryFirstOrDefaultAsync<Resource>(query);
            //return this.unitOfWork.Current.QuerySingle<Resource>(query);
        }

        public Task<IEnumerable<Resource>> FetchDoctorWeek()
        {
            var where = $@" WHERE 1=1 and ";

            var query = $@"SELECT LV.""LookupValueId"" as ""Id"", LV.""Name"" as ""Value"", LV.""LookupId"" as ""OptionalId"",  L.""Name"" as ""Name"", LV.""RowColor"" as ""OptionalText""
	                                FROM ""LookupValue"" LV
 	                                JOIN ""Lookup"" L on L.""LookupId"" = LV.""LookupId""
	                                {where} L.""Name"" = 'DoctorWeek'";

            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> OutPatientsAsync(string? searchParam, int locationId)
        {
            var where = " where 1=1 ";
            if (locationId != 0)
            {
                where += $@" and Apt.""LocationId""={locationId}";
            }
            if (!string.IsNullOrEmpty(searchParam))
            {
                where += $@" AND (TRIM(UPPER(pat.""FullName"")) ILIKE '%{searchParam.Trim().ToUpper()}%' OR pat.""Mobile"" ILIKE '%{searchParam.Trim().ToUpper()}%' OR pat.""UMRNo"" ILIKE '%{searchParam.Trim().ToUpper()}%' OR pat.""Email"" ILIKE '%{searchParam.Trim().ToUpper()}%' OR Apt.""AdmissionNo"" ILIKE '%{searchParam.Trim().ToUpper()}%' ) AND pat.""Active"" IS TRUE";
            }
            var query = $@"SELECT DISTINCT Apt.""PatientId"" AS ""Id"", pat.""FullName"" AS ""Value"",pat.""Mobile"" as ""OptionalText2"",pat.""UMRNo"" as ""OptionalText1""


                                FROM ""Appointment"" Apt
                    left join ""Patient"" pat on pat.""PatientId""=Apt.""PatientId""
            {where} ORDER BY 2 ASC";

            return this.unitOfWork.Current.QueryAsync<Resource>(query);

        }
        public Task<IEnumerable<Resource>> FetchHealthCardAsync()
        {
            var where = $@" WHERE 1=1 and ";

            var query = $@"SELECT hc.""HealthCardId"" as ""Id"",hc.""HealthCardName"" as ""Value""
	                                FROM ""HealthCard"" hc
 	                                ";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> AmbulancesAsync(string? searchParam, int locationId)
        {
            var where = " where 1=1 ";
            where += $@"  AND ab.""Active"" IS TRUE";
            if (locationId != 0)
            {
                where += $@" and ab.""LocationId""={locationId}";
            }
            if (!string.IsNullOrEmpty(searchParam))
            {
                where += $@" AND (TRIM(UPPER(ab.""AmbulanceNo"")) ILIKE '%{searchParam.Trim().ToUpper()}%' ";
            }
            var query = $@"SELECT DISTINCT ab.""AmbulanceId"" AS ""Id"", ab.""AmbulanceNo"" AS ""Value"",ab.""AssignedNo"" as ""OptionalText2""


                                FROM ""Ambulance"" ab
                    left join ""Location"" l on l.""LocationId""=ab.""LocationId""
            {where} ORDER BY 2 ASC";

            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        public Task<IEnumerable<Resource>> DriverDetailAsync(string? searchParam)
        {
            var where = " where 1=1";
            where += $@"  and dr.""Active""IS TRUE";

            if (!string.IsNullOrEmpty(searchParam))
            {
                where += $@" AND (TRIM(UPPER(dr.""DriverDetailName"")) ILIKE '%{searchParam.Trim().ToUpper()}%'  AND ab.""Active"" IS TRUE";
            }
            var query = $@"SELECT DISTINCT dr.""DriverDetailId"" AS ""Id"", dr.""DriverDetailName"" AS ""Value""
                                FROM ""DriverDetail"" dr

            {where} ORDER BY 2 ASC";

            return this.unitOfWork.Current.QueryAsync<Resource>(query);

        }

        public Task<IEnumerable<Resource>> FetchReasons()
        {
            var query = $@"select   ""ReasonsId"" as ""Id"", ""Reason"" as ""Name"" from ""Reasons"" where ""Active"" is true";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> FetchAuthorityMasters()
        {
            var query = $@"select  ""AuthorityMasterId"" as ""Id"", ""Authority"" as ""Name"" from ""AuthorityMaster"" where ""Active"" is true";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> FetchDoctorUnit(int? locationId)
        {
            var where = " where  ";
            if (locationId != null)
            {
                where += $@" ""LocationId""={locationId} and ";
            }
            var query = $@"select  ""DoctorUnitMasterId"" as ""Id"", ""UnitName"" as ""value""  from ""DoctorUnitMaster""  {where} ""Active"" is true ";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> FetchProviderSignature()
        {

            var query = $@"select  ""ProviderId"" as ""Id"", ""FullName"" as ""Name"",  CONCAT('{this.runningEnvironment.CurrentEnvironment}',  '/', ""Guid"", '/',  ""Signature"") as ""Value"" from ""Provider"" where ""Signature"" is not null";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);

        }

        public Task<IEnumerable<Resource>> FetchConsultDoctors(string? searchParam, int locationId)
        {
            var where = " where 1=1 ";
            if (locationId != 0)
            {
                where += $@" and LAM.""LocationId""={locationId}";
            }
            if (!string.IsNullOrEmpty(searchParam))
            {
                where += $@"  AND (TRIM(UPPER(p.""FullName"")) ILIKE '%{searchParam.Trim().ToUpper()}%')  AND p.""Active"" IS TRUE";
            }

            var query = $@"select distinct  p.""ProviderId"" as ""Id"", p.""FullName"" as ""Value"" from ""Provider"" p
left join ""ProviderAvailability"" pl on pl.""ProviderId"" = p.""ProviderId""
JOIN ""Account"" act ON act.""ReferenceId"" = p.""ProviderId"" AND  act.""RoleId"" = '3'
join ""LocationAccountMap"" LAM on LAM.""AccountId"" = act.""AccountId""
{where} ORDER BY 2 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> FetchMedicationFrequencyAsync(string type)
        {
            var where = $@"where 1=1 and ""Active"" is true ";
            if (!string.IsNullOrEmpty(type))
            {
                where += $@" and ""FreqType"" = '{type}'  ";
            }

            var query = $@"select ""MedFrequencyMasterId"" as ""Id"", ""FrequencyName"" as ""Name"", ""FrequencyDescription"" as ""Value"",""CalculationUnit"" as ""OptionalId"" from ""MedFrequencyMaster""
                                 {where}
                                order by ""FrequencyName"" desc";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> FetchRegisteredPatientsAsync(string? searchParam, string? fromDate, string? toDate)
        {
            var where = " WHERE 1 = 1 ";
            if (fromDate != "null")
            {
                where += $@" and P.""CreatedDate""::date >='{fromDate}'::date";
            }
            if (toDate != "null")
            {
                where += $@" and  P.""CreatedDate""::date <='{toDate}'::date";
            }

            if (!string.IsNullOrEmpty(searchParam))
            {
                where += $@" AND (TRIM(UPPER(P.""FullName"")) ILIKE '%{searchParam.Trim().ToUpper()}%' OR P.""Mobile"" ILIKE '%{searchParam.Trim().ToUpper()}%' OR P.""UMRNo"" ILIKE '%{searchParam.Trim().ToUpper()}%') AND P.""Active"" IS TRUE and P.""PaymentStatus"" IS TRUE";
            }

            var query = $@"SELECT DISTINCT P.""PatientId"" AS ""Id"",P.""FullName"" as ""Value"",P.""UMRNo"" as ""OptionalText1"",
                        P.""Mobile"" as ""OptionalText2""
                        FROM ""Receipt"" R
                        join ""Patient"" P on P.""PatientId"" = R.""RespectiveId""  {where} ORDER BY 2 ASC";

            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }




        /// <inheritdoc/>
        public Task<IEnumerable<Resource>> FetchProviderLocationsAsync(int? providerId, int? locationId)
        {
            var where = " WHERE 1= 1 ";
            if (providerId != null)
            {
                where += $@" AND Pr.""ProviderId"" = {providerId} and Pr.""Active"" is true";
            }

            if (locationId != null)
            {
                where += $@" AND ls.""LocationId"" = {locationId}";
            }

            var query = $@"Select distinct ""ProviderId"" ""OptionalId1"", Lac.""LocationId"" ""Id"", Lc.""Name""
                            from ""Provider"" Pr
							join ""Account"" Ac on Ac.""ReferenceId"" = Pr.""ProviderId""
							join ""LocationAccountMap"" Lac on Lac.""AccountId"" = Ac.""AccountId""
							join ""Location"" Lc on Lc.""LocationId"" = Lac.""LocationId""

                            {where}";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }


        public Task<IEnumerable<Resource>> FetchSpecializationProviderAsync(int? specializationId)
        {
            var where = $@"where 1=1 and pr.""Active"" is true ";
            if (specializationId != null)
            {
                where += $@" and s.""SpecializationId"" in ({specializationId})";
            }

            var query = $@"select pr.""ProviderId"" as ""Id"", pr.""FullName"" as ""Name"" from ""Provider"" pr
                        join ""Specialization"" s on s.""SpecializationId"" = ANY (pr.""Specializations"")
                                 {where}
                                order by ""ProviderId"" desc";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public Task<IEnumerable<Resource>> ScanDistinctOutPatients(string fromDate, string toDate, int locationId)
        {
            var query = $@"select distinct bs.""PatientId"" as ""Id"",p.""FullName"" as ""name"" from ""BookScanAppointment"" bs
					left join ""Patient"" p on p.""PatientId"" = bs.""PatientId""
                     where bs.""AppointmentDate"" >= '{fromDate}' and bs.""AppointmentDate""  <= '{toDate}'  and  bs.""LocationId"" = {locationId}";

            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public Task<IEnumerable<Resource>> ScanBulkRCPatients(string fromDate, string toDate, int locationId)
        {
            var query = $@"select distinct bs.""PatientId"" as ""Id"",p.""FullName"" as ""name"",bs.""ScanMachineMasterId"" as ""OptionalId"",smm.""MachineName"" as ""OptionalText"",bs.""ScanTestMasterId"" as ""OptionalId1"",stm.""ScanTestName"" as ""OptionalText1"" from ""BookScanAppointment"" bs
					 left join ""Patient"" p on p.""PatientId"" = bs.""PatientId""
					 left join ""ScanMachineMaster"" smm on smm.""ScanMachineMasterId"" = bs.""ScanMachineMasterId""
					 left join ""ScanTestMaster"" stm on stm.""ScanTestMasterId"" = bs.""ScanTestMasterId""
                     where bs.""Status"" != 'C' and bs.""Active"" is true and bs.""AppointmentDate"" >= '{fromDate}' and bs.""AppointmentDate""  <= '{toDate}'  and  bs.""LocationId"" = {locationId}";

            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public Task<IEnumerable<Resource>> PackageModules(int locationId, string packageType, string moduleType)
        {
            var query = $@"select distinct PM.""PackageModuleId"" as ""Id"", PM.""PackageName"" as ""Name""
                        from ""PackageModule"" PM
                        JOIN ""LookupValue"" PTL ON PTL.""LookupValueId"" = PM.""PackageTypeId""
                        JOIN ""LookupValue"" MTL ON MTL.""LookupValueId"" = PM.""ModuleTypeId""
                        where PM.""LocationId"" = {locationId} and PTL.""Name"" ILIKE '%{packageType}%' and MTL.""Name"" ILIKE '%{moduleType}%'";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> CounsellingTypes()
        {
            var query = $@"SELECT DISTINCT ""LookupValueId"" AS ""Id"", ""Name"", ""LookupId"" as ""OptionalText2""
                                FROM ""LookupValue""
								where ""LookupId"" = (Select ""LookupId"" from ""Lookup"" where ""Name"" = 'Counselling Type')
								ORDER BY ""Name"" ASC";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> PackageTypes()
        {
            var query = $@"SELECT DISTINCT ""LookupValueId"" AS ""Id"", ""Name"", ""LookupId"" as ""OptionalText2""
                                FROM ""LookupValue""
								where ""LookupId"" = (Select ""LookupId"" from ""Lookup"" where ""Name"" = 'Package Type')
								ORDER BY ""Name"" ASC";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<Resource>> ModuleTypes()
        {
            var query = $@"SELECT DISTINCT ""LookupValueId"" AS ""Id"", ""Name"", ""LookupId"" as ""OptionalText2""
                                FROM ""LookupValue""
								where ""LookupId"" = (Select ""LookupId"" from ""Lookup"" where ""Name"" = 'Module Type')
								ORDER BY ""Name"" ASC";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> DietGuidlines(int? typeId)
        {
            var where = $@" where dgl.""Active"" IS TRUE";
            if (typeId != null)
            {
                where += $@" and dgl.""DietTypeId"" = {typeId}";
            }
            var query = $@"select dgl.""DietGuidLinesId"" as ""Id"",dgl.""ContentType""as ""Value"",dgl.""DietGuidLinesName"" as ""Name"",(CASE WHEN dgl.""DocumentUrl"" IS NOT NULL THEN CONCAT('{this.runningEnvironment.CurrentEnvironment}', '/',dgl.""DietGuidLinesName"",'/', dgl.""DocumentUrl"") ELSE NULL END) as ""OptionalText""
                        from ""DietGuidLines"" dgl {where}";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> DietTypes()
        {
            var query = $@"select dt.""DietTypeId"" as ""Id"",dt.""Name"" as ""Name"" from ""DietType"" dt";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public async Task<IEnumerable<Resource>> DoctorAppointmentNoticeAsync(int? locationId, int? providerId, string? appointmentDate)
        {
            var query = $@"SELECT Da.""Description"" ""Value"", Da.""DoctorAppointmentNoticeId"" as ""Id"", Da.""LocationId"" ""OptionalData"", Da.""ProviderId"" ""OptionalId""
	                                FROM ""DoctorAppointmentNotice"" Da

                        where Da.""LocationId"" = {locationId} and Da.""ProviderId"" = {providerId} and
            '{appointmentDate}'::Date >= Da.""FromDate""::Date and '{appointmentDate}'::date <=  Da.""ToDate""::Date and Da.""Active"" is true";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public async Task<IEnumerable<Resource>> ScanAppointmentNoticeAsync(int? locationId, int? machineId, string? appointmentDate)
        {
            var query = $@"SELECT Da.""Description"" ""Value"", Da.""ScanAppointmentNoticeId"" as ""Id"", Da.""LocationId"" ""OptionalData"", Da.""MachineId"" ""OptionalId"", Da.""Availability"" as ""OptionalText""
                     FROM ""ScanAppointmentNotice"" Da where Da.""LocationId"" = {locationId} and Da.""MachineId"" = {machineId} and
            '{appointmentDate}'::Date >= Da.""FromDate""::Date and '{appointmentDate}'::date <=  Da.""ToDate""::Date and Da.""Active"" is true";

            //      var query = $@"SELECT Da.""Description"" ""Value"", Da.""ScanAppointmentNoticeId"" as ""Id"", Da.""LocationId"" ""OptionalData"", Da.""MachineId"" ""OptionalId""
            //               FROM ""ScanAppointmentNotice"" Da where Da.""LocationId"" = {locationId} and Da.""MachineId"" = {machineId} and Da.""Active"" is true
            //and Da.""Availability"" like '%{appointmentDate}%'";


            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }


        public async Task<IEnumerable<Resource>> FetchEmergencyDetailAsync(int? emergencyTypeId)
        {
            var query = $@"select et.""EmergencyTypeName"" as ""Value"",e.""EmergencyDetailId"" as ""Id"",e.""DetailName"" as ""Name"",et.""EmergencyTypeId"" as ""OptionalId"" from ""EmergencyDetail"" e
left join ""EmergencyType"" et on et.""EmergencyTypeId"" = e.""EmergencyTypeId""";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public async Task<IEnumerable<Resource>> FetchLabVacutainersAsync()
        {
            var query = $@"select * from ""LabVacutainer"" where ""Active"" is true";
            var result = await this.unitOfWork.Current.QueryAsync<LabVacutainerModel>(query);
            return result.Select(l =>

                new Resource
                {
                    Id = l.LabVacutainerId,
                    Value = l.LabVacutainerName
                }
            );
        }

        /// <inheritdoc />
        public async Task<IEnumerable<Resource>> FetchAncNumberAsync(int patientId)
        {
            var query = $@"select ""ANCNo"" as ""Value"" from ""ANCCardGeneration"" where ""PatientId"" = {patientId} and ""Active"" is true";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public async Task<IEnumerable<Resource>> FetchPatientBMI(int patientId)
        {
            var query = $@"select ""Measure"" as ""Value"" from ""ObEncounter"" where ""PatientId"" = {patientId}";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <inheritdoc />
        public async Task<IEnumerable<Resource>> PatientRegistrationChargeAsync(int locationId)
        {

            var query = $@"SELECT PR.""Name"",
	                        PR.""PatientRegistrationChargeId"" as ""Id"",
	                        L.""Name"" as ""value"",
                            PR.""ChargeCategoryId"" as ""OptionalId""
                        FROM
	                        ""PatientRegistrationCharge"" PR
                         Join ""Location"" L on L.""LocationId"" = PR.""LocationId""

            where PR.""LocationId"" = {locationId} limit 1";


            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public async Task<IEnumerable<Resource>> FetchEncounterLookup()
        {
            var query = $@"	select ""LookupId"" as ""Id"", ""Name"" from ""EncounterLookup""";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        public async Task<IEnumerable<Resource>> FetchScanTestMachinesAsync(int? locationId, int? scanTestMasterId)
        {
            var where = $@" where smm.""Active"" IS TRUE";
            if (scanTestMasterId != null)
            {
                where += $@" and smtm.""ScanTestMasterId"" = {scanTestMasterId}";
            }
            if (locationId != null)
            {
                where += $@" and smtm.""LocationId"" = {locationId}";
            }
            var query = $@"select smm.""ScanMachineMasterId"" as ""Id"", smm.""MachineName"" as ""Name"" from ""ScanMachineTestMap"" smtm
                            left join ""ScanMachineMaster"" smm on smm.""ScanMachineMasterId"" = smtm.""ScanMachineMasterId"" {where}";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }


        public async Task<IEnumerable<Resource>> FetchEncounterLookUpValues(int encounterLookUpId)
        {
            var where = $@"where 1=1  ";
            if (encounterLookUpId != 0)
            {
                where += $@" and ""LookupId"" in ({encounterLookUpId})";
            }
            var query = $@"	select ""LookupValueId"" as ""Id"", ""Name"" from ""EncounterLookupValue"" {where}";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public async Task<IEnumerable<Resource>> FetchAdmissionPatients(string? searchParams, int? locationId)
        {
            var where = " WHERE 1 = 1 ";

            if (!string.IsNullOrEmpty(searchParams))
            {
                where += $@" AND (TRIM(UPPER(pt.""FullName"")) ILIKE '%{searchParams}%' OR pt.""Mobile"" ILIKE '%{searchParams.Trim()}%' OR pt.""UMRNo"" ILIKE '%{searchParams.Trim()}%') AND pt.""Active"" IS TRUE";
            }

            var querry = $@"select ad.""AdmissionId"" as ""Id"", pt.""FullName"" as ""Name"", ""Mobile"" as ""OptionalText1"", ""UMRNo"" as ""OptionalText2""
                        from ""Admission"" ad
                        join ""Patient"" pt on pt.""PatientId""=ad.""PatientId"" {where}";
            return await this.unitOfWork.Current.QueryAsync<Resource>(querry);

        }

        public async Task<IEnumerable<Resource>> FetchParentPatients(int? parentPatientId)
        {
            var where = " WHERE 1 = 1 ";

            if (parentPatientId != null)
            {
                where += $@" and  ""ParentPatientId""={parentPatientId}";
            }

            var querry = $@"select ""PatientId"" as ""Id"", ""FullName"" as ""Name""
                        from ""Patient""  {where}";
            return await this.unitOfWork.Current.QueryAsync<Resource>(querry);
        }

        /// <inheritdoc />
        public async Task<IEnumerable<Resource>> FetchLabMastersAsync()
        {
            var query = $@"select ""LabMainDetailId"" as ""Id"", ""TestName"" as ""Value"", ""TestCode"" as ""Name"" from ""LabMainDetail"" where ""Active"" is true";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public async Task<IEnumerable<Resource>> FetchWareHouseRetailStoreAsync(int locationId)
        {
            var where = " WHERE 1 = 1 ";

            if (locationId != null)
            {
                where += $@" and  ""LocationId""={locationId}";
            }
            var query = $@"select t.""RetailName"" as ""Values"" from 
	(select  RP. ""RetailName""
		   from ""RetailWareHouseLink"" RWL
		left join  ""RetailPharmacy"" RP on RP.""RetailPharmacyId""=RWL.""RetailPharmacyId""
		left join  ""PharmacyWareHouse"" PW on PW.""PharmacyWareHouseId""=RWL.""PharmacyWareHouseId""
		where ""LocationId""='1') t
	 
union
select t.""WareHouseName"" as ""Values"" from 
(select   PW.""WareHouseName""
		   from ""RetailWareHouseLink"" RWL
		left join  ""RetailPharmacy"" RP on RP.""RetailPharmacyId""=RWL.""RetailPharmacyId""
		left join  ""PharmacyWareHouse"" PW on PW.""PharmacyWareHouseId""=RWL.""PharmacyWareHouseId""
		where ""LocationId""='1') t
	
";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> FetchWareHousesAsync(int id)
        {
            var where = $@" WHERE ""LocationId"" = {id}";
            var query = $@"SELECT ""PharmacyWareHouseId"" AS ""Id"", ""WareHouseName"" AS ""Value"" FROM ""PharmacyWareHouse"" {where} ORDER BY 1 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        
        public Task<IEnumerable<Resource>> FetchRetailsAsync(int wId)
        {
            var where = $@" WHERE ""PharmacyWareHouseId"" = {wId}";
            var query = $@"select RP.""RetailPharmacyId"" AS ""Id"" , RP. ""RetailName"" AS ""Value"" from ""RetailWareHouseLink"" p
left join ""RetailPharmacy"" RP on RP.""RetailPharmacyId""=p.""RetailPharmacyId"" 
{where} ORDER BY 1 ASC";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);

        }

        public Task<IEnumerable<Resource>> FetchTemplatesAsync()
        {
            var where = $@" where th.""Active"" IS TRUE";
            var query = $@"select ""TemplateHeaderId"" as ""Id"" ,""TemplateName"" as ""Value"" From ""TemplateHeader"" th
                 {where}      order by 1 asc";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        public Task<IEnumerable<Resource>> FetchModulesMasterAsync()
        {
            var query = $@"select ""ModulesMasterId"" as ""Id"" ,""ModuleName"" as ""Value"" From ""ModulesMaster"" 
                   order by 1 asc";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
        public Task<IEnumerable<Resource>> FetchAllLabAsync()
        {
           
            var query = $@"select lmd.""LabMainDetailId"" as ""Id"" ,lmd.""TestName"" as ""Value"" from ""LabMainDetail"" lmd
";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);

        }


        /// <inheritdoc />
        public Task<IEnumerable<Resource>> FetchProvidersLocation(int? departmentId, int? locationId)
        {
            var where = $@" WHERE pr2.""Active"" = true and prl.""Active"" is true";
            if (departmentId != null)
            {
                where += $@" AND pr2.""DepartmentId"" = {departmentId} ";
            }
            if (locationId != null)
            {
                where += $@" and prl.""LocationId""= {locationId}";
            }

            //var query = $@"SELECT DISTINCT  prl.""ProviderLocationId"" as ""OptionalData"",pr2.""FullName"" as ""Value"",
            //d.""DepartmentName"" AS ""OptionalText"", d.""DepartmentId"" AS ""OptionalId"",pr2.""ProviderId"" AS ""Id"",
            //(CASE WHEN pr2.""ThumbnailUrl"" IS NOT NULL THEN CONCAT('{this.amazonS3Configuration.BucketURL}', pr2.""Guid"", '/', pr2.""ThumbnailUrl"") ELSE NULL END) AS ""OptionalText2""
            //  FROM ""ProviderLocation"" prl
            //JOIN ""Location"" pral on pral.""LocationId"" = prl.""LocationId"" AND pral.""Active"" IS TRUE
            //JOIN ""Practice"" pra on pra.""PracticeId"" = pral.""PracticeId"" AND pra.""Active"" IS TRUE
            //JOIN ""Provider"" pr2 on pr2.""ProviderId"" = prl.""ProviderId"" and pr2.""Active"" is true
            //JOIN ""Department"" d on d.""DepartmentId"" = pr2.""DepartmentId""
            //{where}  ORDER BY pr2.""FullName"" ";

            //var query = $@" SELECT DISTINCT pr2.""ProviderId"" AS ""Id"",pr2.""FullName"" as ""Value"", --prl.""ProviderAvailabilityId"" as ""OptionalData"" ,
            //                d.""DepartmentName""  AS ""OptionalText"" , d.""DepartmentId"" AS ""OptionalId"",  prl.""LocationId"",
            //                (CASE WHEN pr2.""ThumbnailUrl"" IS NOT NULL THEN CONCAT('{this.amazonS3Configuration.BucketURL}', pr2.""Guid"", '/', pr2.""ThumbnailUrl"") ELSE NULL END) AS ""OptionalText2"",A.""UserName"" AS ""OptionalText1""
            //                from ""Provider"" pr2
            //                join ""ProviderAvailability"" prl on   prl.""ProviderId"" = pr2.""ProviderId""
            //                join ""Specialization"" s on s.""SpecializationId"" = ANY(pr2.""Specializations"") and s.""Active"" = true
            //                join ""Location"" l on l.""LocationId"" = prl.""LocationId""
            //                JOIN ""Department"" d on d.""DepartmentId"" = pr2.""DepartmentId""
            //                JOIN ""Practice"" pra on pra.""PracticeId"" = l.""PracticeId"" AND pra.""Active"" IS TRUE
            //                left join ""Account"" A on A.""ReferenceId"" = pr2.""ProviderId"" and A.""RoleId"" = {(int)Roles.Provider}
            //                   { where}  ORDER BY pr2.""FullName"" ";

            // Doctor names are repeating based on there SpecializationId, so removed this so that doctor name is shown only once.
            //var query = $@"SELECT DISTINCT  on (pr2.""ProviderId"", s.""SpecializationId"") prl.""ProviderAvailabilityId"" ,pr2.""FullName"" as ""Value""
            //, d.""DepartmentName"" AS ""OptionalText"" , d.""DepartmentId"" AS ""OptionalId""
            //,pr2.""ProviderId"" AS ""Id""
            //, s. ""SpecializationId""  AS ""OptionalData"", s.""SpecializationName"" AS ""OptionalText1""
            //, prl.""LocationId"", prl.""ConsultationTypeId""
            //                           FROM ""ProviderAvailability"" prl
            //                           JOIN ""Provider"" pr2 on pr2.""ProviderId"" = prl.""ProviderId"" and pr2.""Active"" is true
            //						   join ""Specialization"" s on s.""SpecializationId"" = ANY (pr2.""Specializations"")
            //                           JOIN ""Location"" pral on pral.""LocationId"" = prl.""LocationId"" AND pral.""Active"" IS TRUE
            //                           JOIN ""Practice"" pra on pra.""PracticeId"" = pral.""PracticeId"" AND pra.""Active"" IS TRUE
            //						   JOIN ""Department"" d on d.""DepartmentId"" = pr2.""DepartmentId""
            //						   { where} and s.""Active"" = true
            //						 ORDER BY pr2.""ProviderId"" ";

            var query = $@"SELECT DISTINCT  on (pr2.""ProviderId"") prl.""ProviderAvailabilityId"" ,pr2.""FullName"" as ""Value""
            , d.""DepartmentName"" AS ""OptionalText"" , d.""DepartmentId"" AS ""OptionalId""
            ,pr2.""ProviderId"" AS ""Id""
            , s. ""SpecializationId""  AS ""OptionalData"", s.""SpecializationName"" AS ""OptionalText1""
            , prl.""LocationId"", prl.""ConsultationTypeId"", pr2.""DoctorType"" AS ""Type""
                                       FROM ""ProviderAvailability"" prl
                                       JOIN ""Provider"" pr2 on pr2.""ProviderId"" = prl.""ProviderId"" and pr2.""Active"" is true
            						   join ""Specialization"" s on s.""SpecializationId"" = ANY (pr2.""Specializations"")
                                       JOIN ""Location"" pral on pral.""LocationId"" = prl.""LocationId"" AND pral.""Active"" IS TRUE
                                       JOIN ""Practice"" pra on pra.""PracticeId"" = pral.""PracticeId"" AND pra.""Active"" IS TRUE
            						   JOIN ""Department"" d on d.""DepartmentId"" = pr2.""DepartmentId""
            						   {where} and s.""Active"" = true
            						 ORDER BY pr2.""ProviderId"" ";

            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        }

        /// <summary>
        /// Fetches all lab external agencies asynchronous.
        /// </summary>
        /// <returns></returns>
        public Task<IEnumerable<Resource>> FetchAllLabExternalAgenciesAsync()
        {
            var query = $@"select ""ExternalLabAgencyId"" as ""Id"", ""AgencyName"" as ""Value"",""AgencyCode"" as ""OptionalText"" from ""ExternalLabAgency""";
            return  this.unitOfWork.Current.QueryAsync<Resource>(query);
            
        }

        /// <summary>
        /// Fetches all active lab external agencies asynchronous.
        /// </summary>
        /// <returns></returns>
        public async Task<IEnumerable<Resource>> FetchAllActiveLabExternalAgenciesAsync()
        {
            var query = $@"select * from ""ExternalLabAgency"" where ""Active"" is true";
            var result = await this.unitOfWork.Current.QueryAsync<ExternalLabAgencyModel>(query);
            return result.Select(l =>

                new Resource
                {
                    Id = l.ExternalLabAgencyId,
                    Value = l.AgencyName,
                    OptionalText = l.AgencyCode
                }
            );
        }

        /// <inheritdoc />
        public Task<IEnumerable<Resource>> FetchLocationChargeTemplateAsync(int? admissionPayTypeId, int? locationId)
        {
            var where = $@" where 1=1 and CT.""IsInUse""=true";
            if (locationId != null)
            {
                where += $@" and CT.""LocationId"" = {locationId}";
            }
            if (admissionPayTypeId != null) {
                where += $@" and IT.""AdmissionPayTypeId"" = {admissionPayTypeId}";
            }
            var query = $@"select IT.""InsuranceTemplateId"" as ""Id"", IT.""ChargeModuleTemplateId"" ""OptionalId"", IT.""InsuranceCompanyId"" ""OptionalData"", IT.""TpaId"" ""OptionalId1"", CT.""TemplateName""  ""Name"", TP.""Name"" as ""Value"", IC.""FullName"" as ""OptionalText"" 
                from ""InsuranceTemplate"" IT
                Join ""ChargeModuleTemplate"" CT on CT.""ChargeModuleTemplateId"" = IT.""ChargeModuleTemplateId""
                JOIN ""Location"" l ON l.""LocationId""= CT.""LocationId"" AND l.""Active"" IS TRUE
                Join ""InsuranceCompany"" IC on IC.""InsuranceCompanyId"" = IT.""InsuranceCompanyId""
                Join ""Tpa"" TP on TP.""TpaId"" = IT.""TpaId""
                                    {where} 
                ORDER BY CT.""IsInUse"" DESC, CT.""CreatedDate"" DESC;";
            return this.unitOfWork.Current.QueryAsync<Resource>(query);
        } 
        
        /// <inheritdoc />
        public async Task<IEnumerable<Resource>> FetchDietConditions()
        {
            var query = $@"SELECT ""ConditionId"" ""Id"",""ConditionName"" ""Name"" FROM ""DietConditionHeader"" where ""Active"" IS TRUE order by ""ConditionName"" asc";
            return await this.unitOfWork.Current.QueryAsync<Resource>(query);
        }
    }
}