protected void DisallowAddEditIfNoPermissions()
    {
        // if its a booking note
        // only allow add/edit if by the provider of the booking, or by a "principle" staff memeber

        UserView userView        = UserView.GetInstance();
        int      loggedInStaffID = Session["StaffID"] == null ? -1 : Convert.ToInt32(Session["StaffID"]);

        Booking booking = BookingDB.GetByEntityID(GetFormID());

        if (booking != null)
        {
            bool canAddEdit = (booking.Provider != null && loggedInStaffID == booking.Provider.StaffID) || userView.IsPrincipal || userView.IsStakeholder;
            if (!canAddEdit)
            {
                GrdNote.FooterRow.Visible = false;
                for (int i = 0; i < GrdNote.Columns.Count; i++)
                {
                    if (GrdNote.Columns[i].HeaderText.Trim() == ".")
                    {
                        GrdNote.Columns[i].Visible = false;
                    }
                }
            }
        }
    }
    protected Tuple <string, string, string, string> GetReferrersEmail()
    {
        if (!IsValidFormID())
        {
            return(null);
        }

        Booking booking = BookingDB.GetByEntityID(GetFormID());

        if (booking == null || booking.Patient == null)
        {
            return(null);
        }

        PatientReferrer[] patientReferrer = PatientReferrerDB.GetActiveEPCPatientReferrersOf(booking.Patient.PatientID);
        if (patientReferrer.Length == 0)
        {
            return(null);
        }

        PatientReferrer  currentPatRegReferrer = patientReferrer[patientReferrer.Length - 1];
        RegisterReferrer curRegReferrer        = currentPatRegReferrer.RegisterReferrer;

        //string refName = curRegReferrer.Referrer.Person.Surname + ", " + curRegReferrer.Referrer.Person.Firstname + " [" + curRegReferrer.Organisation.Name + "]" + " [" + currentPatRegReferrer.PatientReferrerDateAdded.ToString("dd-MM-yyyy") + "]";
        //SetErrorMessage("Name: " + refName);

        string[] emails = ContactDB.GetEmailsByEntityID(currentPatRegReferrer.RegisterReferrer.Organisation.EntityID);
        if (emails.Length == 0)
        {
            return(null);
        }

        string refEmail           = string.Join(",", emails);
        string refName            = (curRegReferrer.Referrer.Person.Title.ID == 0 ? "Dr." : curRegReferrer.Referrer.Person.Title.Descr) + " " + curRegReferrer.Referrer.Person.Surname;
        string bookingOrg         = booking.Organisation.Name;
        string bookingPatientName = booking.Patient.Person.FullnameWithoutMiddlename;

        return(new Tuple <string, string, string, string>(refEmail, refName, bookingOrg, bookingPatientName));
    }
    protected void GrdNote_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        Label        lblId       = (Label)GrdNote.Rows[e.RowIndex].FindControl("lblId");
        DropDownList ddlNoteType = (DropDownList)GrdNote.Rows[e.RowIndex].FindControl("ddlNoteType");
        DropDownList ddlBodyPart = (DropDownList)GrdNote.Rows[e.RowIndex].FindControl("ddlBodyPart");
        TextBox      txtText     = (TextBox)GrdNote.Rows[e.RowIndex].FindControl("txtText");
        //DropDownList ddlSite = (DropDownList)GrdNote.Rows[e.RowIndex].FindControl("ddlSite");
        DropDownList ddlDate_Day   = (DropDownList)GrdNote.Rows[e.RowIndex].FindControl("ddlDate_Day");
        DropDownList ddlDate_Month = (DropDownList)GrdNote.Rows[e.RowIndex].FindControl("ddlDate_Month");
        DropDownList ddlDate_Year  = (DropDownList)GrdNote.Rows[e.RowIndex].FindControl("ddlDate_Year");

        DataTable dt = ViewState["noteinfo_data"] as DataTable;

        DataRow[] foundRows = dt.Select("note_id=" + lblId.Text);
        Note      note      = NoteDB.Load(foundRows[0]);

        DateTime date = GetDate(ddlDate_Day.SelectedValue, ddlDate_Month.SelectedValue, ddlDate_Year.SelectedValue);

        NoteDB.Update(Convert.ToInt32(lblId.Text), date, Convert.ToInt32(Session["StaffID"]), Convert.ToInt32(ddlNoteType.SelectedValue), Convert.ToInt32(ddlBodyPart.SelectedValue), txtText.Text, note.Site.SiteID);



        // if its a booking note
        // email admin so they know if a provider is sabotaging the system (it has happened before)

        int loggedInStaffID = Session["StaffID"] == null ? -1 : Convert.ToInt32(Session["StaffID"]);

        Booking booking = BookingDB.GetByEntityID(GetFormID());

        if (booking != null)  // if note is for a booking
        {
            int thresholdCharacters   = 50;
            int totalCharactersBefore = note.Text.Trim().Length;
            int totalCharactersAfter  = txtText.Text.Trim().Length;
            int difference            = totalCharactersAfter - totalCharactersBefore;

            if (totalCharactersBefore > thresholdCharacters && totalCharactersAfter < thresholdCharacters && difference < -20)
            {
                string mailText = @"This is an administrative email to notify you that notes for a booking may have been deleted.

<u>Logged-in user performing the udate</u>
" + StaffDB.GetByID(loggedInStaffID).Person.FullnameWithoutMiddlename + @"

<u>Original Text (Characters: " + totalCharactersBefore + @")</u>
<font color=""blue"">" + note.Text.Replace(Environment.NewLine, "<br />") + @"</font>

<u>Updated Text (Characters: " + totalCharactersAfter + @")</u>
<font color=""blue"">" + txtText.Text.Replace(Environment.NewLine, "<br />") + @"</font>

<u>Booking details</u>
<table border=""0"" cellpadding=""2"" cellspacing=""2""><tr><td>Booking ID:</td><td>" + booking.BookingID + @"</td></tr><tr><td>Booking Date:</td><td>" + booking.DateStart.ToString("d MMM, yyyy") + " " + booking.DateStart.ToString("h:mm") + (booking.DateStart.Hour < 12 ? "am" : "pm") + @"</td></tr><tr><td>Organisation:</td><td>" + booking.Organisation.Name + @"</td></tr><tr><td>Provider:</td><td>" + booking.Provider.Person.FullnameWithoutMiddlename + @"</td></tr><tr><td>Patient:</td><td>" + (booking.Patient == null ? "" : booking.Patient.Person.FullnameWithoutMiddlename + " [ID:" + booking.Patient.PatientID + "]") + @"</td></tr><tr><td>Status:</td><td>" + booking.BookingStatus.Descr + @"</td></tr></table>

Regards,
Mediclinic
";
                bool   EnableDeletedBookingsAlerts = Convert.ToInt32(SystemVariableDB.GetByDescr("EnableDeletedBookingsAlerts").Value) == 1;

                if (EnableDeletedBookingsAlerts && !Utilities.IsDev())
                {
                    Emailer.AsyncSimpleEmail(
                        ((SystemVariables)Session["SystemVariables"])["Email_FromEmail"].Value,
                        ((SystemVariables)Session["SystemVariables"])["Email_FromName"].Value,
                        ((SystemVariables)Session["SystemVariables"])["AdminAlertEmail_To"].Value,
                        "Notification that booking notes may have been deleted",
                        mailText.Replace(Environment.NewLine, "<br />"),
                        true,
                        null);
                }
            }
        }



        GrdNote.Columns[7].Visible = true;
        GrdNote.EditIndex          = -1;
        FillNoteGrid();
    }
    protected void FillNoteGrid()
    {
        if (!IsValidFormID())
        {
            if (!Utilities.IsDev() || Request.QueryString["id"] != null)
            {
                HideTableAndSetErrorMessage();
                return;
            }

            // can still view all if dev and no id set .. but no insert/edit
            GrdNote.Columns[5].Visible = false;
        }

        if (!IsValidFormScreen() && !Utilities.IsDev())
        {
            HideTableAndSetErrorMessage();
            return;
        }


        DataTable dt = IsValidFormID() ? NoteDB.GetDataTable_ByEntityID(GetFormID(), null, true, true) : NoteDB.GetDataTable(true);


        if (IsValidFormScreen())
        {
            Hashtable allowedNoteTypes = new Hashtable();
            DataTable noteTypes        = ScreenNoteTypesDB.GetDataTable_ByScreenID(GetFormScreen());
            for (int i = 0; i < noteTypes.Rows.Count; i++)
            {
                allowedNoteTypes[Convert.ToInt32(noteTypes.Rows[i]["note_type_id"])] = 1;
            }

            for (int i = dt.Rows.Count - 1; i >= 0; i--)
            {
                if (allowedNoteTypes[Convert.ToInt32(dt.Rows[i]["note_type_id"])] == null)
                {
                    dt.Rows.RemoveAt(i);
                }
            }
        }

        UserView userView         = UserView.GetInstance();
        bool     canSeeModifiedBy = userView.IsStakeholder || userView.IsMasterAdmin;

        dt.Columns.Add("last_modified_note_info_visible", typeof(Boolean));
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            dt.Rows[i]["last_modified_note_info_visible"] = canSeeModifiedBy;
        }


        ViewState["noteinfo_data"] = dt;



        // add note info to hidden field to use when emailing notes

        string emailBodyText = string.Empty;

        Booking booking = BookingDB.GetByEntityID(GetFormID());

        if (booking != null)
        {
            emailBodyText += @"<br /><br />
<u>Treatment Information</u>
<br />
<table border=""0"" cellpadding=""0"" cellspacing=""0"">" +
                             (booking.Patient == null ? "" : @"<tr><td>Patient</td><td style=""width:10px;""></td><td>" + booking.Patient.Person.FullnameWithoutMiddlename + @"</td></tr>") +
                             (booking.Offering == null ? "" : @"<tr><td>Service</td><td></td><td>" + booking.Offering.Name + @"</td></tr>") + @"
    <tr><td>Date</td><td></td><td>" + booking.DateStart.ToString("dd-MM-yyyy") + @"</td></tr>
    <tr><td>Provider</td><td></td><td>" + booking.Provider.Person.FullnameWithoutMiddlename + @"</td></tr>
</table>";
        }

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            Note n = NoteDB.Load(dt.Rows[i]);
            emailBodyText += "<br /><br /><u>Note (" + n.DateAdded.ToString("dd-MM-yyyy") + ")</u><br />" + n.Text.Replace(Environment.NewLine, "<br />");
        }
        emailText.Value = emailBodyText + "<br /><br />" + SystemVariableDB.GetByDescr("LettersEmailSignature").Value;;



        if (dt.Rows.Count > 0)
        {
            if (IsPostBack && ViewState["noteinfo_sortexpression"] != null && ViewState["noteinfo_sortexpression"].ToString().Length > 0)
            {
                DataView dataView = new DataView(dt);
                dataView.Sort      = ViewState["noteinfo_sortexpression"].ToString();
                GrdNote.DataSource = dataView;
            }
            else
            {
                GrdNote.DataSource = dt;
            }


            try
            {
                GrdNote.DataBind();
            }
            catch (Exception ex)
            {
                this.lblErrorMessage.Visible = true;
                this.lblErrorMessage.Text    = ex.ToString();
            }
        }
        else
        {
            dt.Rows.Add(dt.NewRow());
            GrdNote.DataSource = dt;
            GrdNote.DataBind();

            int TotalColumns = GrdNote.Rows[0].Cells.Count;
            GrdNote.Rows[0].Cells.Clear();
            GrdNote.Rows[0].Cells.Add(new TableCell());
            GrdNote.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            GrdNote.Rows[0].Cells[0].Text       = "No Record Found";
        }


        Tuple <string, string, string, string> refsEmailInfo = GetReferrersEmail();
        ImageButton btnEmail = GrdNote.HeaderRow.FindControl("btnEmail") as ImageButton;

        if (refsEmailInfo != null)
        {
            btnEmail.Visible = true;
            ((HiddenField)GrdNote.HeaderRow.FindControl("hiddenRefEmail")).Value           = refsEmailInfo.Item1;
            ((HiddenField)GrdNote.HeaderRow.FindControl("hiddenRefName")).Value            = refsEmailInfo.Item2;
            ((HiddenField)GrdNote.HeaderRow.FindControl("hiddenBookingOrg")).Value         = refsEmailInfo.Item3;
            ((HiddenField)GrdNote.HeaderRow.FindControl("HiddenBookingPatientName")).Value = refsEmailInfo.Item4;
        }
        else
        {
            btnEmail.Visible = false;
        }

        DisallowAddEditIfNoPermissions(); // place this after databinding
    }
    protected void CreateNoteFile(string tmpFilename)
    {
        string header = string.Empty;

        Booking booking = BookingDB.GetByEntityID(GetFormID());

        if (booking != null)
        {
            Site site = SiteDB.GetByID(Convert.ToInt32(Session["SiteID"]));

            string[] phNums;
            if (Utilities.GetAddressType().ToString() == "Contact")
            {
                phNums = ContactDB.GetByEntityID(-1, booking.Organisation.EntityID, 34).Select(r => r.AddrLine1).ToArray();
            }
            else if (Utilities.GetAddressType().ToString() == "ContactAus")
            {
                phNums = ContactAusDB.GetByEntityID(-1, booking.Organisation.EntityID, 34).Select(r => r.AddrLine1).ToArray();
            }
            else
            {
                throw new Exception("Unknown AddressType in config: " + Utilities.GetAddressType().ToString().ToString());
            }

            if (phNums.Length == 0)
            {
                if (Utilities.GetAddressType().ToString() == "Contact")
                {
                    phNums = ContactDB.GetByEntityID(-1, site.EntityID, 34).Select(r => r.AddrLine1).ToArray();
                }
                else if (Utilities.GetAddressType().ToString() == "ContactAus")
                {
                    phNums = ContactAusDB.GetByEntityID(-1, site.EntityID, 34).Select(r => r.AddrLine1).ToArray();
                }
                else
                {
                    throw new Exception("Unknown AddressType in config: " + Utilities.GetAddressType().ToString().ToString());
                }
            }

            string numbers = string.Empty;
            if (phNums.Length > 0)
            {
                numbers += " - TEL " + phNums[0];
            }
            if (phNums.Length > 1)
            {
                numbers += ", " + phNums[1];
            }

            header += site.Name + numbers + Environment.NewLine;
            header += "Clinic:  " + booking.Organisation.Name + Environment.NewLine;

            if (booking.Patient != null)
            {
                header += "Patient:  " + booking.Patient.Person.FullnameWithoutMiddlename + Environment.NewLine;
            }
            if (booking.Offering != null)
            {
                header += "Service:  " + booking.Offering.Name + Environment.NewLine;
            }

            header += "Provider:  " + booking.Provider.Person.FullnameWithoutMiddlename + Environment.NewLine;
            header += "Date of Consultation: " + booking.DateStart.ToString("d MMM yyyy") + Environment.NewLine + Environment.NewLine + "Treatment Note:" + Environment.NewLine;
        }


        System.Collections.ArrayList notesList = new System.Collections.ArrayList();
        foreach (GridViewRow row in GrdNote.Rows)
        {
            Label    lblId    = row.FindControl("lblId") as Label;
            Label    lblText  = row.FindControl("lblText") as Label;
            CheckBox chkPrint = row.FindControl("chkPrint") as CheckBox;

            if (lblId == null || lblText == null || chkPrint == null)
            {
                continue;
            }

            if (chkPrint.Checked)
            {
                notesList.Add(header + lblText.Text.Replace("<br/>", "\n"));
            }
        }

        if (notesList.Count == 0)
        {
            throw new CustomMessageException("Please select at least one note to print.");
        }

        UserView userView     = UserView.GetInstance();
        bool     isAgedCare   = booking != null && booking.Organisation != null ? booking.Organisation.IsAgedCare : userView.IsAgedCareView;
        string   filename     = isAgedCare ? "BlankTemplateAC.docx" : "BlankTemplate.docx";
        string   originalFile = Letter.GetLettersDirectory() + filename;

        if (!System.IO.File.Exists(originalFile))
        {
            throw new CustomMessageException("Template File '" + filename + "' does not exist.");
        }

        string errorString = string.Empty;

        if (!WordMailMerger.Merge(originalFile, tmpFilename, null, null, 0, false, true, (string[])notesList.ToArray(typeof(string)), false, null, out errorString))
        {
            throw new CustomMessageException("Error:" + errorString);
        }
    }