namespace Hims.Api.Senders
{
    using System;
    using System.Threading.Tasks;
    using Dapper;

    using Hims.Domain.Configurations;
    using Newtonsoft.Json;
    using Hims.Domain.Helpers;
    using Hims.Domain.Services;
    using Hims.Domain.Repositories.UnitOfWork;
    using Hims.Shared.DataFilters;
    using Hims.Shared.EntityModels;
    using Hims.Shared.Library;
    using Hims.Shared.UserModels;
    using RestSharp;

    /// <inheritdoc />
    public class SMSSender : ISMSSender
    {
        /// <summary>
        /// The application configuration.
        /// </summary>
        private readonly IApplicationConfiguration applicationConfiguration;

        /// <summary>
        /// The SMS helper.
        /// </summary>
        private readonly ISMSHelper smsHelper;

        /// <summary>
        /// The SMS sender.
        /// </summary>
        private readonly IKaleyraSMSHelper kaleyraSMSHelper;

        /// <summary>
        /// The country services.
        /// </summary>
        private readonly ICountryService countryServices;

        /// <summary>
        /// The country services.
        /// </summary>
        private readonly IUnitOfWork unitOfWork;

        /// <summary>
        /// The SMS server error.
        /// </summary>
        private readonly string smsServerError;

        /// <summary>
        /// The sms log services.
        /// </summary>
        private readonly ISmsLogService smsLogService;


        /// <inheritdoc cref="ISMSSender" />
        public SMSSender(IApplicationConfiguration applicationConfiguration, ISMSHelper smsHelper, ICountryService countryServices, IKaleyraSMSHelper kaleyraSMSHelper, IUnitOfWork unitOfWork, ISmsLogService smsLogService)
        {
            this.applicationConfiguration = applicationConfiguration;
            this.smsHelper = smsHelper;
            this.countryServices = countryServices;
            this.kaleyraSMSHelper = kaleyraSMSHelper;
            this.unitOfWork = unitOfWork;
            this.smsLogService = smsLogService;
            //this.smsServerError = "Due to SMS server issue we are unable to send messages at this moment. Please contact an administrator for further details.";
            this.smsServerError = "SUCCESS";
        }

        /// <inheritdoc />
        public async Task<OTPResponse> SendOTPAsync(string mobile, int countryId, string otp)
        {
            string where = "";
            if (mobile.ToLower().Contains("umr"))
            {
                where += $@"where UPPER(p.""UMRNo"") = '{mobile.Trim().ToUpper()}'";
                var query = $@"select p.""PatientId"",p.""Mobile"",p.""CountryId"" from ""Patient""p {where}";

                var patientData = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<PatientModel>(query);
                if (patientData == null)
                {
                    return null;
                }
                countryId = 1;
                mobile = patientData.Mobile;
            }
            var country = await this.countryServices.FindAsync(countryId);
            var text = $@"Select * from ""Practice"" limit 1";

            var practice = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<PracticeModel>(text);

            var messageBody = $@"{otp} is your";

            if (practice != null)
            {
                messageBody += $" {practice.FullName}- ";
            }
            messageBody += $@" Careaxes verification code. The verification code is confidential. For security reasons, do not share this code with anyone.";
            var otpResponse = await this.kaleyraSMSHelper.SendSMSAsync(mobile, messageBody, country, "1207162031731062187");

            var quary = $@"INSERT INTO public.""SMSLog""(""Response"", ""SendedDate"", ""ReceiverNumber"")
                           VALUES ('{otpResponse.Content}', now(), '{country.CountryCode + mobile}'); ";

            await this.unitOfWork.Current.ExecuteAsync(quary);
            

            //if (!otpResponse.IsSuccessful)
            //{
            //    otpResponse = await this.smsHelper.SendSMSAsync(mobile, $"{otp} is your {text}- Careaxes verification code. The verification code is confidential. For security reasons, do not share this code with anyone.", country);
            //}

            return otpResponse == null || !otpResponse.IsSuccessful ? new OTPResponse { OTP = otp, OTPExpiresIn = 180, Error = true, ErrorDescription = this.smsServerError } : new OTPResponse { OTP = otp, OTPExpiresIn = 180 };
        }

        /// <inheritdoc />
        public async Task<bool> SendVideoLinkAsync(string mobile, int countryId, string link, string patientName, string providerName)
        {
            var country = await this.countryServices.FindAsync(countryId);
            var smsResponse = await this.kaleyraSMSHelper.SendSMSAsync(mobile, $"Hi {patientName}! Click on the link to join the video call with {providerName}. {link} - Virtual Steth Team", country, "1207162739139826333");

            var quary = $@"INSERT INTO public.""SMSLog""(""Response"", ""SendedDate"", ""ReceiverNumber"")
	                          VALUES ('{smsResponse.Content}', now(), '{country.CountryCode + mobile}'); ";

            await this.unitOfWork.Current.ExecuteAsync(quary);

            if (!smsResponse.IsSuccessful)
            {
                smsResponse = await this.smsHelper.SendSMSAsync(mobile, $"{link} is your Careaxes video conference link.", country);
            }

            return smsResponse != null && smsResponse.IsSuccessful;
        }

        /// <inheritdoc />
        public async Task<bool> SendReferralCodeSMSAsync(string mobile, int countryId, string referralCode, string fullName, string link)
        {
            try
            {
                var country = await this.countryServices.FindAsync(countryId);
                var message = $"Your friend {fullName} has invited you to join Careaxes. Book an Appointment with India's Best Doctors and get Discounts. Use Code -{referralCode} at Singup. {link}";
                var smsResponse = await this.kaleyraSMSHelper.SendSMSAsync(mobile, message, country, "1207161665327725960");
                smsResponse.Content = JsonConvert.SerializeObject(smsResponse.Content);
                var quary = $@"INSERT INTO public.""SMSLog""(""Response"", ""SendedDate"", ""ReceiverNumber"")
                           VALUES ('{smsResponse.Content}', now(), '{country.CountryCode + mobile}'); ";

                await this.unitOfWork.Current.ExecuteAsync(quary);

                if (!smsResponse.IsSuccessful)
                {
                    smsResponse = await this.smsHelper.SendSMSAsync(mobile, message, country);
                }

                return smsResponse == null || smsResponse.IsSuccessful;
            }
            catch (Exception ex)
            {

            }
            return false;
        }

        /// <inheritdoc />
        public async Task<bool> SendReferralLinkAsync(string mobile, int countryId, string fullName, string iosLink, string androidLink)
        {
            var country = await this.countryServices.FindAsync(countryId);
            var message = $"Dr.{fullName} has invited you to join Careaxes. Book an Appointment with India's Best Doctors and get Discounts. {iosLink},{androidLink}";

            var smsResponse = await this.kaleyraSMSHelper.SendSMSAsync(mobile, message, country, "1207161665327725960");

            var quary = $@"INSERT INTO public.""SMSLog""(""Response"", ""SendedDate"", ""ReceiverNumber"")
	                          VALUES ('{smsResponse.Content}', now(), '{country.CountryCode + mobile}'); ";

            await this.unitOfWork.Current.ExecuteAsync(quary);

            if (!smsResponse.IsSuccessful)
            {
                smsResponse = await this.smsHelper.SendSMSAsync(mobile, message, country);
            }

            return smsResponse == null || smsResponse.IsSuccessful;
        }

        /// <inheritdoc />
        public async Task<bool> SendSMSAsync(string mobile, int countryId, string message, string templateId)
        {
            var country = await this.countryServices.FindAsync(countryId);
            var smsResponse = await this.kaleyraSMSHelper.SendSMSAsync(mobile, message, country, templateId);
            smsResponse.Content = smsResponse.Content.Replace("'", " ");
            var quary = $@"INSERT INTO public.""SMSLog""(""Response"", ""SendedDate"", ""ReceiverNumber"")
	                          VALUES ('{smsResponse.Content}', now(), '{country.CountryCode + mobile}'); ";

            await this.unitOfWork.Current.ExecuteAsync(quary);


            if (!smsResponse.IsSuccessful)
            {
                smsResponse = await this.smsHelper.SendSMSAsync(mobile, message, country);
            }

            return smsResponse == null || !smsResponse.IsSuccessful;
        }

        /// <inheritdoc />
        public async Task<bool> SendWelcomeMessageAsync(string mobile, string fullName, string password, string createPasswordLink, int countryId)
        {
            var country = await this.countryServices.FindAsync(countryId);
            //var text = "Maa Sharadha";

            var text = $@"Select * from ""Practice"" limit 1";

            var practice = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<PracticeModel>(text);

            var messageBody = "Hi Welcome to";

            if (practice != null)
            {

                messageBody += $" {practice.FullName},";

                //var messageBody = string.IsNullOrEmpty(password)
                //                      ? $"Hi {fullName}, Welcome to {text} - Careaxes. Thank you for registering with us. Click on the link below to create your password {createPasswordLink}"
                //                      : $"Hi {fullName}, Welcome to {text} - Careaxes. Thank you for registering with us. Click on the link below to create your password {this.applicationConfiguration.WebsiteLink}";

            }
            messageBody += $@" -Careaxes. Thank you for registering with us. Click on the link below to create your password {createPasswordLink}";
            var smsResponse = await this.kaleyraSMSHelper.SendSMSAsync(mobile, messageBody, country, "1207162031747904710");
            var quary = $@"INSERT INTO public.""SMSLog""(""Response"", ""SendedDate"", ""ReceiverNumber"")
	                          VALUES ('{smsResponse.Content}', now(), '{country.CountryCode + mobile}'); ";

            await this.unitOfWork.Current.ExecuteAsync(quary);

            //if (!smsResponse.IsSuccessful)
            //{
            //    smsResponse = await this.smsHelper.SendSMSAsync(mobile, messageBody, country);
            //}

            return smsResponse != null && smsResponse.IsSuccessful;
        }

        /// <inheritdoc />
        public async Task<bool> SendTicketMessageAsync(string mobile, string ticketNumber, int countryId)
        {
            var country = await this.countryServices.FindAsync(countryId);

            //var text = "Maa Sharadha";

            var text = $@"Select * from ""Practice"" limit 1";

            var practice = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<PracticeModel>(text);

            var messageBody = $@"Thanks for reaching out to us. A ticket has been raised with Reference ID: {ticketNumber}. Please save this ID for future references. - Careaxes,";

            if (practice != null)
            {

                messageBody += $@" {practice.FullName}";
            }
            var smsResponse = await this.kaleyraSMSHelper.SendSMSAsync(mobile, messageBody, country, "1207162031739756090");

            var quary = $@"INSERT INTO public.""SMSLog""(""Response"", ""SendedDate"", ""ReceiverNumber"")
	                          VALUES ('{smsResponse.Content}', now(), '{country.CountryCode + mobile}'); ";

            await this.unitOfWork.Current.ExecuteAsync(quary);

            //if (!smsResponse.IsSuccessful)
            //{
            //    smsResponse = await this.smsHelper.SendSMSAsync(mobile, messageBody, country);
            //}

            return smsResponse != null && smsResponse.IsSuccessful;
        }

        /// <inheritdoc />
        public async Task<bool> SendPanicTicketMessageAsync(string mobile, string ticketNumber, int countryId)
        {
            var country = await this.countryServices.FindAsync(countryId);
            var messageBody = $@"We have alerted the doctor about an Emergency call request! Thanks for reaching out to us. A ticket has been raised with Reference ID: {ticketNumber}. Please note this for future reference.";

            var smsResponse = await this.kaleyraSMSHelper.SendSMSAsync(mobile, messageBody, country, "1207161665456703858");

            var quary = $@"INSERT INTO public.""SMSLog""(""Response"", ""SendedDate"", ""ReceiverNumber"")
	                          VALUES ('{smsResponse.Content}', now(), '{country.CountryCode + mobile}'); ";

            await this.unitOfWork.Current.ExecuteAsync(quary);

            //if (!smsResponse.IsSuccessful)
            //{
            //    smsResponse = await this.smsHelper.SendSMSAsync(mobile, messageBody, country);
            //}

            return smsResponse != null && smsResponse.IsSuccessful;
        }

        /// <inheritdoc />
        public async Task<bool> SendPanicTicketMessageToUserAsync(string mobile, string ticketNumber, int countryId, string message, string templateId)
        {
            var country = await this.countryServices.FindAsync(countryId);
            var messageBody = message;
            var smsResponse = await this.kaleyraSMSHelper.SendSMSAsync(mobile, messageBody, country, templateId);

            var quary = $@"INSERT INTO public.""SMSLog""(""Response"", ""SendedDate"", ""ReceiverNumber"")
	                          VALUES ('{smsResponse.Content}', now(), '{country.CountryCode + mobile}'); ";

            await this.unitOfWork.Current.ExecuteAsync(quary);

            //if (!smsResponse.IsSuccessful)
            //{
            //    smsResponse = await this.smsHelper.SendSMSAsync(mobile, messageBody, country);
            //}

            return smsResponse != null && smsResponse.IsSuccessful;
        }

        /// <inheritdoc />
        public async Task<bool> SendTicketClosedMessageAsync(string mobile, string ticketNumber, int countryId)
        {
            var country = await this.countryServices.FindAsync(countryId);
            //var text = "Maa Sharadha";

            var text = $@"Select * from ""Practice"" limit 1";

            var practice = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<PracticeModel>(text);

            var messageBody = "Your ticket with Reference ID. {ticketNumber} has been addressed and closed. Thank you! -Careaxes, ";

            if (practice != null)
            {
                messageBody += $@"{practice.FullName}";
            }
            var smsResponse = await this.kaleyraSMSHelper.SendSMSAsync(mobile, messageBody, country, "1207162031702944232");
            var quary = $@"INSERT INTO public.""SMSLog""(""Response"", ""SendedDate"", ""ReceiverNumber"")
	                          VALUES ('{smsResponse.Content}', now(), '{country.CountryCode + mobile}'); ";

            await this.unitOfWork.Current.ExecuteAsync(quary);

            //if (!smsResponse.IsSuccessful)
            //{
            //    smsResponse = await this.smsHelper.SendSMSAsync(mobile, messageBody, country);
            //}

            return smsResponse != null && smsResponse.IsSuccessful;
        }

        /// <inheritdoc />
        public async Task<bool> SendAppointmentMessageAsync(AppointmentModel appointment, string messageType, string displayTime)
        {
            //var text = "Maa Sharadha";

            var text = $@"Select * from ""Practice"" limit 1";

            //var practice = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<PracticeModel>(text);
            var text2 = $@"select l.""LocationId"",l.""Name"",l.""PracticeId"",p.""FullName"" as ""PracticeName"" from ""Location"" l
                           join ""Practice"" p on p.""PracticeId"" = l.""PracticeId"" where ""LocationId"" = {appointment.LocationId} limit 1";

            var Location = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<LocationModel>(text2);
            var messageBody = $@"Hi {appointment.PatientName?.ToUpper()} , your Appointment with Dr.{appointment.ProviderName?.ToUpper()} on {appointment.AppointmentDate:dd MMMM yyyy} {displayTime} is confirmed. Your reference number is {appointment.AppointmentNo}. - Careaxes, ";

            if (Location.PracticeName != null)
            {
                messageBody += $"{Location.PracticeName}";
            }
            var templateId = "1207162031771390021";
            if (messageType == "has been rescheduled successfully")
            {
                messageBody = $"Hi {appointment.PatientName?.ToUpper()}! Your appointment has been successfully rescheduled with Dr {appointment.ProviderName?.ToUpper()} on {appointment.AppointmentDate:dd MMMM yyyy} {displayTime}. Your reference number - {appointment.AppointmentNo}. - Careaxes, {Location.PracticeName}";
                templateId = "1207162031713978240";
            }
            if (messageType == "has been cancelled")
            {
                messageBody = $"Hi {appointment.PatientName?.ToUpper()}, Your appointment with Dr {appointment.ProviderName?.ToUpper()} has been cancelled successfully. Your reference number {appointment.AppointmentNo}. - Careaxes, {Location.PracticeName}";
                templateId = "1207162031709201734";
            }
            var country = await this.countryServices.FindAsync(appointment.PatientCountryId);

            if (country == null)
            {
                return false;
            }

            if (!string.IsNullOrEmpty(appointment.PatientMobile))
            {
                var smsResponse = await this.kaleyraSMSHelper.SendSMSAsync(appointment.PatientMobile, messageBody, country, templateId);

                //var quary = $@"INSERT INTO public.""SMSLog""(""Response"", ""SendedDate"", ""ReceiverNumber"")
                //           VALUES ('{smsResponse.Content}', '{DateTime.UtcNow}', '{country.CountryCode + appointment.PatientMobile}'); ";
                var smsLogModel = new SMSLogModel
                {
                    Response = smsResponse.Content,
                    SendedDate = DateTime.UtcNow,
                    ReceiverNumber = country.CountryCode + appointment.PatientMobile
                };
                await this.smsLogService.Insert(smsLogModel);
                // await this.unitOfWork.Current.ExecuteAsync(quary);

                //if (!smsResponse.IsSuccessful)
                //{
                //    await this.smsHelper.SendSMSAsync(appointment.PatientMobile, messageBody, country);
                //}
            }

            messageBody = $"Hi Dr {appointment.ProviderName?.ToUpper()}, Patient {appointment.PatientName?.ToUpper()} {messageType} an appointment with you on {appointment.AppointmentDate:dd MMMM yyyy} {displayTime}. - Careaxes, {Location.PracticeName}";
            templateId = "1207162031845457190";

            country = await this.countryServices.FindAsync(appointment.ProviderCountryId);

            if (!string.IsNullOrEmpty(appointment.ProviderMobile) && appointment.EnableSMSAlerts == true)
            {
                var smsResponse = await this.kaleyraSMSHelper.SendSMSAsync(appointment.ProviderMobile, messageBody, country, templateId);

                var quary = $@"INSERT INTO public.""SMSLog""(""Response"", ""SendedDate"", ""ReceiverNumber"")
	                          VALUES ('{smsResponse.Content}', now(), '{country.CountryCode + appointment.ProviderMobile}'); ";

                await this.unitOfWork.Current.ExecuteAsync(quary);

                //if (!smsResponse.IsSuccessful)
                //{
                //    await this.smsHelper.SendSMSAsync(appointment.ProviderMobile, messageBody, country);
                //}
            }
            
            return true;
        }

        /// <inheritdoc />
        public async Task<bool> SendPaymentMessageAsync(AppointmentModel appointment, string displayTime)
        {
            //var text = "Maa Sharadha";

            var text = $@"Select * from ""Practice"" limit 1";

            var practice = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<PracticeModel>(text);

            var messageBody = $@"Hi {appointment.PatientName?.ToUpper()}, We have received your payment and your appointment has been successfully booked with Dr. {appointment.ProviderName?.ToUpper()}. Your Reference number is {appointment.AppointmentNo}. - Careaxes,";

            if (practice != null)
            {
                messageBody += $" {practice.FullName}";
            }
            var country = await this.countryServices.FindAsync(appointment.PatientCountryId);

            if (country == null)
            {
                return false;
            }

            if (!string.IsNullOrEmpty(appointment.PatientMobile))
            {
                var smsResponse = await this.kaleyraSMSHelper.SendSMSAsync(appointment.PatientMobile, messageBody, country, "1207162031756363864");

                var quary = $@"INSERT INTO public.""SMSLog""(""Response"", ""SendedDate"", ""ReceiverNumber"")
	                          VALUES ('{smsResponse.Content}', now(), '{country.CountryCode + appointment.PatientMobile}'); ";

                await this.unitOfWork.Current.ExecuteAsync(quary);

                //if (!smsResponse.IsSuccessful)
                //{
                //    await this.smsHelper.SendSMSAsync(appointment.PatientMobile, messageBody, country);
                //}
            }
            messageBody = $"Hi Dr {appointment.ProviderName?.ToUpper()}, Patient {appointment.PatientName?.ToUpper()} booked an appointment with you on {appointment.AppointmentDate:dd MMMM yyyy} {displayTime}. - Careaxes, {practice?.FullName}";
            country = await this.countryServices.FindAsync(appointment.PatientCountryId);

            if (!string.IsNullOrEmpty(appointment.ProviderMobile) && appointment.EnableSMSAlerts == true)
            {
                var smsResponse = await this.kaleyraSMSHelper.SendSMSAsync(appointment.ProviderMobile, messageBody, country, "1207161665432718357");

                var quary = $@"INSERT INTO public.""SMSLog""(""Response"", ""SendedDate"", ""ReceiverNumber"")
	                          VALUES ('{smsResponse.Content}', now(), '{country.CountryCode + appointment.ProviderMobile}'); ";

                await this.unitOfWork.Current.ExecuteAsync(quary);

                //if (!smsResponse.IsSuccessful)
                //{
                //    await this.smsHelper.SendSMSAsync(appointment.ProviderMobile, messageBody, country);
                //}
            }

            return true;
        }

        /// <inheritdoc />
        public async Task<bool> SendResetPasswordAsync(string mobile, string fullName, string accountType, string resetPasswordLink, int countryId)
        {
            var country = await this.countryServices.FindAsync(countryId);
            var msg = $"1 hour";
            var messageBody = $"Hi {fullName}, Click on the link below to reset your password in {accountType}, you have {msg} to pick your password. After that, you'll have to ask for a new link. -Careaxes, {resetPasswordLink}";
            var smsResponse = await this.kaleyraSMSHelper.SendSMSAsync(mobile, messageBody, country, "1207162031691546485");

            var quary = $@"INSERT INTO public.""SMSLog""(""Response"", ""SendedDate"", ""ReceiverNumber"")
	                          VALUES ('{smsResponse.Content}', now(), '{country.CountryCode + mobile}'); ";

            await this.unitOfWork.Current.ExecuteAsync(quary);

            if (!smsResponse.IsSuccessful)
            {
                smsResponse = await this.smsHelper.SendSMSAsync(mobile, messageBody, country);
            }

            return smsResponse != null && smsResponse.IsSuccessful;
        }

        /// <inheritdoc />
        public async Task<bool> SendCreatePasswordAsync(string mobile, string fullName, string createPasswordLink, int countryId)
        {
            var country = await this.countryServices.FindAsync(countryId);
            var messageBody = $"Hi {fullName}, your account with {"Careaxes"}- Careaxes has been successfully created. To login, click on the link and create your password {createPasswordLink}";

            var smsResponse = await this.kaleyraSMSHelper.SendSMSAsync(mobile, messageBody, country, "1207162031722557699");

            var quary = $@"INSERT INTO public.""SMSLog""(""Response"", ""SendedDate"", ""ReceiverNumber"")
	                          VALUES ('{smsResponse.Content}', now(), '{country.CountryCode + mobile}'); ";

            await this.unitOfWork.Current.ExecuteAsync(quary);

            if (!smsResponse.IsSuccessful)
            {
                smsResponse = await this.smsHelper.SendSMSAsync(mobile, messageBody, country);
            }

            return smsResponse != null && smsResponse.IsSuccessful;
        }

        /// <inheritdoc />
        public async Task<bool> SendRescheduleInfoToProviderAsync(string mobile, string providerName, string patientName, int countryId, string date, string displayTime)
        {
            //var text = "Maa Sharadha";

            var text = $@"Select * from ""Practice"" limit 1";

            var practice = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<PracticeModel>(text);

            var messageBody = $@"Hi Dr {providerName}! Patient {patientName} has been rescheduled an appointment with you on {date} {displayTime}. - Careaxes, ";
            var country = await this.countryServices.FindAsync(countryId);
            if (practice != null)
            {

                messageBody += $"{practice.FullName}";
            }
            var smsResponse = await this.kaleyraSMSHelper.SendSMSAsync(mobile, messageBody, country, "1207161665338758280");

            var quary = $@"INSERT INTO public.""SMSLog""(""Response"", ""SendedDate"", ""ReceiverNumber"")
	                          VALUES ('{smsResponse.Content}', now(), '{country.CountryCode + mobile}'); ";

            await this.unitOfWork.Current.ExecuteAsync(quary);

            if (!smsResponse.IsSuccessful)
            {
                smsResponse = await this.smsHelper.SendSMSAsync(mobile, messageBody, country);
            }

            return smsResponse != null && smsResponse.IsSuccessful;
        }

        /// <inheritdoc />
        public async Task<Tuple<bool, string>> SendLabReportSms(string mobile, string patientName, string url)
        {
            var country = await this.unitOfWork.Countries.FindAsync(c => c.CountryName == "India");
            var text = $@"Select * from ""Practice"" limit 1";

            var practice = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<PracticeModel>(text);
            if (country == null)
            {
                return new Tuple<bool, string>(false, null);
            }

            var countryModel = new CountryModel
            {
                CountryName = country.CountryName,
                CountryCode = country.CountryCode,
                CountryId = country.CountryId,
                SMSAuthorization = country.SMSAuthorization,
                SMSFrom = country.SMSFrom,
                SMSUrl = country.SMSUrl,
                SMSUsername = country.SMSUsername
            };
            var urls = string.Empty;
            var messageBody = $@"Hello {patientName}, greetings from ";

            if (practice != null)
            {
                messageBody += $"{practice.FullName}";
            }
            messageBody += $@", your LabReport is ready. Click the link ";
            var (smsResponse, urlss) = await this.kaleyraSMSHelper.SendReportSMSAsync(mobile, messageBody, countryModel, "1207164672062171339", url);

            urls = urlss;

            var quary = $@"INSERT INTO public.""SMSLog""(""Response"", ""SendedDate"", ""ReceiverNumber"")
	                          VALUES ('{smsResponse.Content}', now(), '{country.CountryCode + mobile}'); ";

            await this.unitOfWork.Current.ExecuteAsync(quary);

            if (!smsResponse.IsSuccessful)
            {
                (smsResponse, urls) = await this.smsHelper.SendLabReportSMSAsync(mobile, messageBody, countryModel, url);
            }

            return new Tuple<bool, string>(smsResponse != null && smsResponse.IsSuccessful, urls);
        }
        public async Task<bool> SendPdfLinkSms(string patientMobile, object patientName, string createPdfLink)
        {
            var country = await this.unitOfWork.Countries.FindAsync(c => c.CountryName == "India");
            var text = $@"Select * from ""Practice"" limit 1";

            var practice = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<PracticeModel>(text);
            

            var countryModel = new CountryModel
            {
                CountryName = country.CountryName,
                CountryCode = country.CountryCode,
                CountryId = country.CountryId,
                SMSAuthorization = country.SMSAuthorization,
                SMSFrom = country.SMSFrom,
                SMSUrl = country.SMSUrl,
                SMSUsername = country.SMSUsername
            };
            var urls = string.Empty;
            var messageBody = $@"Hello {patientName}, greetings from ";

            if (practice != null)
            {
                messageBody += $"{practice.FullName}";
            }
            messageBody += $@", your DietPlan is ready. Click the link ";
            var (smsResponse, urlss) = await this.kaleyraSMSHelper.SendPdfLinkSMSAsync(patientMobile, messageBody, countryModel, "1207164672062171339", createPdfLink);

            urls = urlss;

            var quary = $@"INSERT INTO public.""SMSLog""(""Response"", ""SendedDate"", ""ReceiverNumber"")
	                          VALUES ('{smsResponse.Content}', now(), '{country.CountryCode + patientMobile}'); ";

            await this.unitOfWork.Current.ExecuteAsync(quary);

            if (!smsResponse.IsSuccessful)
            {
                (smsResponse, urls) = await this.smsHelper.SendLabReportSMSAsync(patientMobile, messageBody, countryModel, createPdfLink);
            }

            return smsResponse != null && smsResponse.IsSuccessful;
        }

        
        
    }
}
