protected void GrdLetterPrintHistory_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        DataTable dt       = Session["letterprinthistory_data"] as DataTable;
        bool      tblEmpty = (dt.Rows.Count == 1 && dt.Rows[0][0] == DBNull.Value);

        if (!tblEmpty && e.Row.RowType == DataControlRowType.DataRow)
        {
            Label     lblId     = (Label)e.Row.FindControl("lblId");
            DataRow[] foundRows = dt.Select("lph_letter_print_history_id=" + lblId.Text);
            DataRow   thisRow   = foundRows[0];

            LetterPrintHistory letterPrintHistory = LetterPrintHistoryDB.LoadAll(thisRow);

            Button btnRetrieveFlatFile = (Button)e.Row.FindControl("btnRetrieveFlatFile");
            if (btnRetrieveFlatFile != null && btnRetrieveFlatFile.CssClass != "hiddencol")
            {
                string historyDir  = Letter.GetLettersHistoryDirectory(thisRow["lph_organisation_id"] == DBNull.Value ? 0 : Convert.ToInt32(thisRow["lph_organisation_id"]));
                string filePath    = historyDir + letterPrintHistory.LetterPrintHistoryID + System.IO.Path.GetExtension(letterPrintHistory.DocName);
                string filePathPDF = historyDir + letterPrintHistory.LetterPrintHistoryID + ".pdf";

                btnRetrieveFlatFile.Visible = System.IO.File.Exists(filePath) || System.IO.File.Exists(filePathPDF);
            }


            HyperLink lnkBookingSheetForPatient = (HyperLink)e.Row.FindControl("lnkBookingSheetForPatient");
            if (lnkBookingSheetForPatient != null)
            {
                if (thisRow["lph_booking_id"] == DBNull.Value)
                {
                    lnkBookingSheetForPatient.Visible = false;
                }
                else
                {
                    int     booking_id = Convert.ToInt32(thisRow["lph_booking_id"]);
                    Booking booking    = BookingDB.GetByID(booking_id);
                    lnkBookingSheetForPatient.NavigateUrl = booking.GetBookingSheetLinkV2();
                }
            }


            Utilities.AddConfirmationBox(e);
            if ((e.Row.RowState & DataControlRowState.Edit) > 0)
            {
                Utilities.SetEditRowBackColour(e, System.Drawing.Color.LightGoldenrodYellow);
            }
        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {
        }
    }
    protected void FillGrid()
    {
        if (!IsValidFormID())
        {
            HideTableAndSetErrorMessage("", "Invalid URL Parameters");
            return;
        }

        Organisation org = OrganisationDB.GetByID(GetFormID());

        if (org == null)
        {
            HideTableAndSetErrorMessage("", "Invalid URL Parameters");
            return;
        }

        lblHeading.Text             = Page.Title = "Manage Registrations For :  " + org.Name;
        this.lnkThisOrg.NavigateUrl = "~/OrganisationDetailV2.aspx?type=view&id=" + GetFormID().ToString();
        this.lnkThisOrg.Text        = "Back to details for " + org.Name;



        string searchSurname = "";

        if (Request.QueryString["surname_search"] != null && Request.QueryString["surname_search"].Length > 0)
        {
            searchSurname         = Request.QueryString["surname_search"];
            txtSearchSurname.Text = Request.QueryString["surname_search"];
        }
        bool searchSurnameOnlyStartsWith = true;

        if (Request.QueryString["surname_starts_with"] != null && Request.QueryString["surname_starts_with"].Length > 0)
        {
            searchSurnameOnlyStartsWith           = Request.QueryString["surname_starts_with"] == "0" ? false : true;
            chkSurnameSearchOnlyStartWith.Checked = searchSurnameOnlyStartsWith;
        }
        else
        {
            chkSurnameSearchOnlyStartWith.Checked = searchSurnameOnlyStartsWith;
        }


        DataTable dt = RegisterPatientDB.GetDataTable_PatientsOf(GetFormViewOnlyLast(), org.OrganisationID, false, false, false, false, searchSurname, searchSurnameOnlyStartsWith);


        int[] ptIDs = new int[dt.Rows.Count];
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            ptIDs[i] = Convert.ToInt32(dt.Rows[i]["patient_id"]);
        }


        // get last and next booking dates

        Hashtable lastBookingDates = BookingDB.GetLastBookingDates(ptIDs, org.OrganisationID);
        Hashtable nextBookingDates = BookingDB.GetNextBookingDates(ptIDs, org.OrganisationID);

        dt.Columns.Add("last_booking_date", typeof(DateTime));
        dt.Columns.Add("next_booking_date", typeof(DateTime));
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            dt.Rows[i]["last_booking_date"] = lastBookingDates[Convert.ToInt32(dt.Rows[i]["patient_id"])] == null ? (object)DBNull.Value : (DateTime)lastBookingDates[Convert.ToInt32(dt.Rows[i]["patient_id"])];
            dt.Rows[i]["next_booking_date"] = nextBookingDates[Convert.ToInt32(dt.Rows[i]["patient_id"])] == null ? (object)DBNull.Value : (DateTime)nextBookingDates[Convert.ToInt32(dt.Rows[i]["patient_id"])];
        }



        // get epc info

        Hashtable mostRecentRecallHashByPatientID = LetterPrintHistoryDB.GetMostRecentRecallHashByPatients(ptIDs);

        Hashtable patientHealthCardCache        = PatientsHealthCardsCacheDB.GetBullkActive(ptIDs);
        Hashtable epcRemainingCache             = GetEPCRemainingCache(patientHealthCardCache);
        Hashtable patientsMedicareCountCache    = PatientsMedicareCardCountThisYearCacheDB.GetBullk(ptIDs, DateTime.Today.Year);
        Hashtable patientsEPCRemainingCache     = PatientsEPCRemainingCacheDB.GetBullk(ptIDs, DateTime.Today.AddYears(-1));
        int       MedicareMaxNbrServicesPerYear = Convert.ToInt32(SystemVariableDB.GetByDescr("MedicareMaxNbrServicesPerYear").Value);


        dt.Columns.Add("epc_expire_date", typeof(DateTime));
        dt.Columns.Add("has_valid_epc", typeof(Boolean));
        dt.Columns.Add("epc_count_remaining", typeof(Int32));

        dt.Columns.Add("most_recent_recall_sent", typeof(DateTime));
        for (int i = dt.Rows.Count - 1; i >= 0; i--)
        {
            int patientID = Convert.ToInt32(dt.Rows[i]["patient_id"]);

            HealthCard hc     = GetHealthCardFromCache(patientHealthCardCache, patientID);
            bool       hasEPC = hc != null && hc.DateReferralSigned != DateTime.MinValue;
            HealthCardEPCRemaining[] epcsRemaining = !hasEPC ? new HealthCardEPCRemaining[] { } : GetEPCRemainingFromCache(epcRemainingCache, hc);
            int totalServicesAllowedLeft           = !hasEPC ? 0 : (MedicareMaxNbrServicesPerYear - (int)patientsMedicareCountCache[patientID]);

            int totalEpcsRemaining = 0;
            for (int j = 0; j < epcsRemaining.Length; j++)
            {
                totalEpcsRemaining += epcsRemaining[j].NumServicesRemaining;
            }

            DateTime referralSignedDate = !hasEPC ? DateTime.MinValue : hc.DateReferralSigned.Date;
            DateTime hcExpiredDate      = !hasEPC ? DateTime.MinValue : referralSignedDate.AddYears(1);
            bool     isExpired          = !hasEPC ? true              : hcExpiredDate <= DateTime.Today;

            int nServicesLeft = 0;
            if (hc != null && DateTime.Today >= referralSignedDate.Date && DateTime.Today < hcExpiredDate.Date)
            {
                nServicesLeft = totalEpcsRemaining;
            }
            if (hc != null && totalServicesAllowedLeft < nServicesLeft)
            {
                nServicesLeft = totalServicesAllowedLeft;
            }

            bool has_valid_epc       = hasEPC && !isExpired && (hc.Organisation.OrganisationID == -2 || (hc.Organisation.OrganisationID == -1 && nServicesLeft > 0));
            int  epc_count_remaining = hasEPC && hc.Organisation.OrganisationID == -1 ? nServicesLeft : -1;

            dt.Rows[i]["has_valid_epc"]       = has_valid_epc;
            dt.Rows[i]["epc_expire_date"]     = hasEPC ? hcExpiredDate : (object)DBNull.Value;
            dt.Rows[i]["epc_count_remaining"] = epc_count_remaining != -1 ? epc_count_remaining : (object)DBNull.Value;

            dt.Rows[i]["most_recent_recall_sent"] = mostRecentRecallHashByPatientID[patientID] == null ? (object)DBNull.Value : ((LetterPrintHistory)mostRecentRecallHashByPatientID[patientID]).Date;
        }



        Session["registerpatienttoorg_data"] = dt;

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


            try
            {
                GrdRegistration.DataBind();
                GrdRegistration.PagerSettings.FirstPageText = "1";
                GrdRegistration.PagerSettings.LastPageText  = GrdRegistration.PageCount.ToString();
                GrdRegistration.DataBind();
            }
            catch (Exception ex)
            {
                HideTableAndSetErrorMessage("", ex.ToString());
            }
        }
        else
        {
            dt.Rows.Add(dt.NewRow());
            GrdRegistration.DataSource = dt;
            GrdRegistration.DataBind();

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

        if (hideFotter)
        {
            GrdRegistration.FooterRow.Visible = false;
        }
    }
    protected void FillGrid()
    {
        DateTime fromDate = DateTime.MinValue; // IsValidDate(txtStartDate.Text) ? GetDate(txtStartDate.Text) : DateTime.MinValue;
        DateTime toDate   = IsValidDate(txtEndDate.Text)   ? GetDate(txtEndDate.Text)   : DateTime.MinValue;
        DateTime nNoRecallLettersAfterDate = IsValidDate(txtNoRecallLettersAfterDate.Text) ? GetDate(txtNoRecallLettersAfterDate.Text) : DateTime.MinValue;


        //DataTable dt = PatientDB.GetRecallPatients(fromDate, toDate, chkOnlyShowIfHasEPCs.Checked, Convert.ToInt32(ddlClinics.SelectedValue));
        DataTable dt = PatientDB.GetRecallPatients(fromDate, toDate, false, Convert.ToInt32(ddlClinics.SelectedValue));



        int[] patientIDs = new int[dt.Rows.Count];
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            patientIDs[i] = Convert.ToInt32(dt.Rows[i]["patient_patient_id"]);
        }


        Hashtable mostRecentRecallHashByPatientID = LetterPrintHistoryDB.GetMostRecentRecallHashByPatients(patientIDs);


        Hashtable patientHealthCardCache        = PatientsHealthCardsCacheDB.GetBullkActive(patientIDs);
        Hashtable epcRemainingCache             = GetEPCRemainingCache(patientHealthCardCache);
        Hashtable patientsMedicareCountCache    = PatientsMedicareCardCountThisYearCacheDB.GetBullk(patientIDs, DateTime.Today.Year);
        Hashtable patientsEPCRemainingCache     = PatientsEPCRemainingCacheDB.GetBullk(patientIDs, DateTime.Today.AddYears(-1));
        int       MedicareMaxNbrServicesPerYear = Convert.ToInt32(SystemVariableDB.GetByDescr("MedicareMaxNbrServicesPerYear").Value);


        ArrayList remainingPatientIDs = new ArrayList();

        dt.Columns.Add("epc_expire_date", typeof(DateTime));
        dt.Columns.Add("has_valid_epc", typeof(Boolean));
        dt.Columns.Add("epc_count_remaining", typeof(Int32));

        dt.Columns.Add("most_recent_recall_sent", typeof(DateTime));
        for (int i = dt.Rows.Count - 1; i >= 0; i--)
        {
            int patientID = Convert.ToInt32(dt.Rows[i]["patient_patient_id"]);

            HealthCard hc     = GetHealthCardFromCache(patientHealthCardCache, patientID);
            bool       hasEPC = hc != null && hc.DateReferralSigned != DateTime.MinValue;
            HealthCardEPCRemaining[] epcsRemaining = !hasEPC ? new HealthCardEPCRemaining[] { } : GetEPCRemainingFromCache(epcRemainingCache, hc);
            int totalServicesAllowedLeft           = !hasEPC ? 0 : (MedicareMaxNbrServicesPerYear - (int)patientsMedicareCountCache[patientID]);

            int totalEpcsRemaining = 0;
            for (int j = 0; j < epcsRemaining.Length; j++)
            {
                totalEpcsRemaining += epcsRemaining[j].NumServicesRemaining;
            }

            DateTime referralSignedDate = !hasEPC ? DateTime.MinValue : hc.DateReferralSigned.Date;
            DateTime hcExpiredDate      = !hasEPC ? DateTime.MinValue : referralSignedDate.AddYears(1);
            bool     isExpired          = !hasEPC ? true              : hcExpiredDate <= DateTime.Today;

            int nServicesLeft = 0;
            if (hc != null && DateTime.Today >= referralSignedDate.Date && DateTime.Today < hcExpiredDate.Date)
            {
                nServicesLeft = totalEpcsRemaining;
            }
            if (hc != null && totalServicesAllowedLeft < nServicesLeft)
            {
                nServicesLeft = totalServicesAllowedLeft;
            }

            bool has_valid_epc       = hasEPC && !isExpired && (hc.Organisation.OrganisationID == -2 || (hc.Organisation.OrganisationID == -1 && nServicesLeft > 0));
            int  epc_count_remaining = hasEPC && hc.Organisation.OrganisationID == -1 ? nServicesLeft : -1;

            dt.Rows[i]["has_valid_epc"]       = has_valid_epc;
            dt.Rows[i]["epc_expire_date"]     = hasEPC ? hcExpiredDate : (object)DBNull.Value;
            dt.Rows[i]["epc_count_remaining"] = epc_count_remaining != -1 ? epc_count_remaining : (object)DBNull.Value;

            dt.Rows[i]["most_recent_recall_sent"] = mostRecentRecallHashByPatientID[patientID] == null ? (object)DBNull.Value : ((LetterPrintHistory)mostRecentRecallHashByPatientID[patientID]).Date;

            // remove if no valid epc and set to show only those with a valid EPC
            if (!chkShowWithEPC.Checked && has_valid_epc)
            {
                dt.Rows.RemoveAt(i);
            }
            else if (!chkShowWithNoEPC.Checked && !has_valid_epc)
            {
                dt.Rows.RemoveAt(i);
            }
            else if (nNoRecallLettersAfterDate != DateTime.MinValue && mostRecentRecallHashByPatientID[patientID] != null && ((LetterPrintHistory)mostRecentRecallHashByPatientID[patientID]).Date.Date > nNoRecallLettersAfterDate)
            {
                dt.Rows.RemoveAt(i);
            }
            else
            {
                remainingPatientIDs.Add(patientID);
            }
        }

        hiddenPatientIDs.Value = string.Join(",", (int[])remainingPatientIDs.ToArray(typeof(int)));

        Session["recallpatientinfo_data"] = dt;


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


            try
            {
                GrdPatient.DataBind();
                GrdPatient.PagerSettings.FirstPageText = "1";
                GrdPatient.PagerSettings.LastPageText  = GrdPatient.PageCount.ToString();
                GrdPatient.DataBind();
            }
            catch (Exception ex)
            {
                SetErrorMessage("", ex.ToString());
            }
        }
        else
        {
            dt.Rows.Add(dt.NewRow());
            GrdPatient.DataSource = dt;
            GrdPatient.DataBind();

            int TotalColumns = GrdPatient.Rows[0].Cells.Count;
            GrdPatient.Rows[0].Cells.Clear();
            GrdPatient.Rows[0].Cells.Add(new TableCell());
            GrdPatient.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            GrdPatient.Rows[0].Cells[0].Text       = "No Record Found";
        }
    }
    protected void GrdLetterPrintHistory_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        //if (e.CommandName.Equals("Insert"))
        //{
        //    DropDownList ddlTitle = (DropDownList)GrdLetterPrintHistory.FooterRow.FindControl("ddlNewTitle");
        //    TextBox txtFirstname = (TextBox)GrdLetterPrintHistory.FooterRow.FindControl("txtNewFirstname");
        //    TextBox txtMiddlename = (TextBox)GrdLetterPrintHistory.FooterRow.FindControl("txtNewMiddlename");
        //    TextBox txtSurname = (TextBox)GrdLetterPrintHistory.FooterRow.FindControl("txtNewSurname");
        //    DropDownList ddlGender = (DropDownList)GrdLetterPrintHistory.FooterRow.FindControl("ddlNewGender");
        //    TextBox txtDOB = (TextBox)GrdLetterPrintHistory.FooterRow.FindControl("txtNewDOB");

        //    CheckBox chkIsDeceased = (CheckBox)GrdLetterPrintHistory.FooterRow.FindControl("chkNewIsDeceased");



        //    string[] dobParts = txtDOB.Text.Trim().Split(new char[] { '-' });
        //    DateTime dob = new DateTime(Convert.ToInt32(dobParts[2]), Convert.ToInt32(dobParts[1]), Convert.ToInt32(dobParts[0]));

        //    Staff loggedInStaff = StaffDB.GetByID(Convert.ToInt32(Session["StaffID"]));
        //    int person_id = PersonDB.Insert(loggedInStaff.Person.PersonID, ddlTitle.SelectedValue, Utilities.FormatName(txtFirstname.Text), Utilities.FormatName(txtMiddlename.Text), Utilities.FormatName(txtSurname.Text), ddlGender.SelectedValue, dob);
        //    LetterPrintHistoryDB.Insert(person_id, chkIsDeceased.Checked, "", "");

        //    FillGrid();
        //}

        if (e.CommandName.Equals("RetrieveLetterDB"))
        {
            int   index = Int32.Parse((string)e.CommandArgument);
            Label lblId = (Label)GrdLetterPrintHistory.Rows[index].FindControl("lblId");

            LetterFile letterFile = LetterPrintHistoryDB.GetLetterFile(Convert.ToInt32(lblId.Text));
            if (letterFile == null)
            {
                throw new CustomMessageException("No file with selected ID");
            }

            Letter.DownloadDocument(Response, letterFile.Contents, letterFile.Name);
        }

        if (e.CommandName.Equals("RetrieveLetterFlatFile"))
        {
            int   index = Int32.Parse((string)e.CommandArgument);
            Label lblId = (Label)GrdLetterPrintHistory.Rows[index].FindControl("lblId");

            LetterPrintHistory letterPrintHistory = LetterPrintHistoryDB.GetByID(Convert.ToInt32(lblId.Text));

            DataTable dt         = Session["letterprinthistory_data"] as DataTable;
            DataRow[] foundRows  = dt.Select("lph_letter_print_history_id=" + lblId.Text);
            DataRow   thisRow    = foundRows[0];
            string    historyDir = Letter.GetLettersHistoryDirectory(thisRow["lph_organisation_id"] == DBNull.Value ? 0 : Convert.ToInt32(thisRow["lph_organisation_id"]));

            string filePath    = historyDir + letterPrintHistory.LetterPrintHistoryID + System.IO.Path.GetExtension(letterPrintHistory.DocName);
            string filePathPDF = historyDir + letterPrintHistory.LetterPrintHistoryID + ".pdf";
            if (!System.IO.File.Exists(filePath) && !System.IO.File.Exists(filePathPDF))
            {
                throw new CustomMessageException("No file with selected ID");
            }

            bool isPDF = System.IO.File.Exists(filePathPDF);

            byte[] fileContents = isPDF ? System.IO.File.ReadAllBytes(filePathPDF) : System.IO.File.ReadAllBytes(filePath);
            Letter.DownloadDocument(Response, fileContents, isPDF ? System.IO.Path.ChangeExtension(letterPrintHistory.DocName, ".pdf") : letterPrintHistory.DocName);
        }
    }
    protected void FillGrid()
    {
        int org_id               = IsValidFormOrganisation() ? GetFormOrganisation(false) :  0;
        int patient_id           = IsValidFormPatient()      ? GetFormPatient(false)      : -1;
        int register_referrer_id = IsValidFormRegReferrer()  ? GetFormRegReferrer(false)  : -1;


        if (patient_id != -1)
        {
            Patient patient = PatientDB.GetByID(patient_id);
            lblHeading.Text         = "Letter Print History For ";
            lnkToEntity.Text        = patient.Person.FullnameWithoutMiddlename;
            lnkToEntity.NavigateUrl = "PatientDetailV2.aspx?type=view&id=" + patient.PatientID;
        }
        else if (org_id != 0)
        {
            Organisation org = OrganisationDB.GetByID(org_id);
            lblHeading.Text         = "Letter Print History For ";
            lnkToEntity.Text        = org.Name;
            lnkToEntity.NavigateUrl = "OrganisationDetailV2.aspx?type=view&id=" + org.OrganisationID;
        }


        DataTable dt = LetterPrintHistoryDB.GetDataTable(DateTime.MinValue, DateTime.MinValue, org_id, patient_id, register_referrer_id, Convert.ToInt32(Session["SiteID"]));

        Session["letterprinthistory_data"] = dt;

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


            try
            {
                GrdLetterPrintHistory.DataBind();
                GrdLetterPrintHistory.PagerSettings.FirstPageText = "1";
                GrdLetterPrintHistory.PagerSettings.LastPageText  = GrdLetterPrintHistory.PageCount.ToString();
                GrdLetterPrintHistory.DataBind();
            }
            catch (Exception ex)
            {
                SetErrorMessage("", ex.ToString());
            }
        }
        else
        {
            dt.Rows.Add(dt.NewRow());
            GrdLetterPrintHistory.DataSource = dt;
            GrdLetterPrintHistory.DataBind();

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