protected void SetInvoiceInfo(Invoice invoice)
    {
        bool isDebug          = Request["debug"] != null && Request["debug"] == "1";
        bool useOnlyTestItems = false;

        SaveType saveType = Request.QueryString["reftag"] != null ? SaveType.Cancellation : SaveType.Claim;

        string receiptString = string.Empty;

        foreach (Receipt receipt in ReceiptDB.GetByInvoice(invoice.InvoiceID, false))
        {
            receiptString += (receiptString.Length == 0 ? "" : ", ") + "$" + receipt.Total.ToString();
        }

        string invoiceViewURL = "/Invoice_ViewV2.aspx?invoice_id=" + invoice.InvoiceID;

        lblInvoiceID.Text      = "<a href=\"" + invoiceViewURL + "\" onclick=\"open_new_tab('" + invoiceViewURL + "');return false;\">" + invoice.InvoiceID + "</a>";
        lblInvoiceTotal.Text   = "$" + invoice.Total.ToString();
        lblInvoiceOwing.Text   = "$" + invoice.TotalDue.ToString();
        lblReceiptedTotal.Text = "$" + invoice.ReceiptsTotal.ToString() + (invoice.CreditNotesTotal == 0 ? "" : " &nbsp;&nbsp;($" + invoice.CreditNotesTotal.ToString() + " Credit Noted)") + (invoice.RefundsTotal == 0 ? "" : " &nbsp;&nbsp;($" + invoice.RefundsTotal.ToString() + " Refunds)");
        lblDebtor.Text         = invoice.GetDebtor(true);
        lblBkDate.Text         = invoice.Booking.DateStart.ToString("d MMM, yyyy");
        lblBkOrgText.Text      = invoice.Booking.Organisation.IsAgedCare? "Facility" : "Clinic";
        lblBkOrg.Text          = invoice.Booking.Organisation.Name;

        System.Data.DataTable tbl = DBBase.GetGenericDataTable_WithWhereOrderClause(null, "Field", "field_id=" + invoice.Booking.Provider.Field.ID, "", "field_id", "descr");
        invoice.Booking.Provider.Field = IDandDescrDB.Load(tbl.Rows[0], "field_id", "descr");

        RegisterStaff regStaff = RegisterStaffDB.GetByStaffIDAndOrganisationID(invoice.Booking.Provider.StaffID, invoice.Booking.Organisation.OrganisationID);

        if (regStaff == null)
        {
            throw new CustomMessageException("Staff Member Not Set To This Clinic/Fac.");
        }

        InvoiceLine[] invLines = InvoiceLineDB.GetByInvoiceID(invoice.InvoiceID);
        Hashtable     patientHealthCardCache = PatientsHealthCardsCacheDB.GetBullkActive(invLines.Select(x => x.Patient.PatientID).ToArray());

        List <TyroHealthPointClaimIten> claimItems = new List <TyroHealthPointClaimIten>();

        for (int i = 0; i < invLines.Length; i++)
        {
            HealthCard hc = GetHealthCardFromCache(patientHealthCardCache, invLines[i].Patient.PatientID);

            string ptURL  = "PatientDetailV2.aspx?type=view&id=" + invLines[i].Patient.PatientID;
            string ptLink = "<a href=\"" + ptURL + "\" onclick=\"open_new_tab('" + ptURL + "');return false;\">" + invLines[i].Patient.Person.FullnameWithoutMiddlename + "</a>";

            if (hc == null)
            {
                throw new CustomMessageException("No healthcard found for " + ptLink + " (PT-ID:" + invLines[i].Patient.PatientID + ")");
            }
            if (hc.Organisation.OrganisationType.OrganisationTypeID != 150)
            {
                throw new CustomMessageException("Healthcard found for " + ptLink + " (PT-ID:" + invLines[i].Patient.PatientID + ") Is Not An Insurance Card");
            }

            /*
             * claim-amount:      claim amount in cents                    - max 10 digits
             * service-code:      item number service code                 - max 5  characters
             * description:       description of item to appear on receipt - max 32 characters
             * service-reference: body part or tooth number suffix         - max 3  characters
             * patient-id:        patient ID on card                       - exactly 2 digits
             * service-date:      claim date in YYYYMMDD format
             */

            isDebug = true;

            claimItems.Add(new TyroHealthPointClaimIten(
                               ((int)(invLines[i].Price * 100)).ToString(),
                               isDebug ? "F1234" : invLines[i].Offering.TacCompanyCode,
                               isDebug ? "Face"  : invLines[i].AreaTreated,
                               invLines[i].ServiceReference,
                               "",      // family number on card -- legally they have to enter it themselves
                               isDebug ? DateTime.Today.ToString("yyyyMMdd") : invoice.Booking.DateStart.ToString("yyyyMMdd")));
        }


        //useOnlyTestItems = true;

        // save variables & JSON array on the page accessable to JS to send to Tyro
        if (useOnlyTestItems)
        {
            claimItems = new List <TyroHealthPointClaimIten>();

            claimItems.Add(new TyroHealthPointClaimIten(
                               "10000",
                               "00001",
                               "SKULL XRAY",
                               "01",
                               "02",
                               DateTime.Today.ToString("yyyyMMdd")));

            claimItems.Add(new TyroHealthPointClaimIten(
                               "15000",
                               "00001",
                               "SKULL XRAY",
                               "01",
                               "02",
                               DateTime.Today.ToString("yyyyMMdd")));

            Page.ClientScript.RegisterStartupScript(this.GetType(), "invoice_items",
                                                    @"<script language=javascript>
                var _providerId       = '4237955J';
                var _serviceType      = 'D';
                var _claimItemsCount  = '2';
                var _totalClaimAmount = '25000';
                var _allClaimItems    = " + new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(claimItems) + @"; 
             </script>");
        }
        else
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "invoice_items",
                                                    @"<script language=javascript>
                    var _providerId       = '" + (isDebug ? "4237955J" : (regStaff.ProviderNumber.Length > 0 ? regStaff.ProviderNumber : invoice.Booking.Provider.ProviderNumber)) + @"';
                    var _serviceType      = '" + GetServiceTypeHashtable()[invoice.Booking.Provider.Field.Descr.ToLower()].ToString() + @"';
                    var _claimItemsCount  = '" + invLines.Length.ToString() + @"';
                    var _totalClaimAmount = '" + ((int)(invLines.Sum(item => item.Price) * 100)).ToString() + @"';
                    var _allClaimItems    = " + new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(claimItems) /* convert to JSON array */ + @"; 
                    " + (saveType == SaveType.Cancellation ? "var _refTag = " + Request.QueryString["reftag"] : string.Empty) + @"
                 </script>");
        }
    }
    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";
        }
    }