Imports System.Data
Imports System.Data.SqlClient
Imports System.Web
Imports RGBC_Forecast

Partial Public Class TestDbConnection
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        Dim sb As New System.Text.StringBuilder()

        ' Test basic connectivity by opening the connection and running a simple query
        Try
            Dim conn = Global.RGBC_Forecast.db.conn
            conn.Open()
            Dim cmd As New SqlCommand("SELECT 1 AS Test, GETDATE() AS ServerTime", conn)
            Dim reader = cmd.ExecuteReader()
            If reader.Read() Then
                sb.Append("<div class='info ok'>✓ Connection OK.</div>")
                sb.Append("<div class='info'>Server time: " & HttpUtility.HtmlEncode(reader("ServerTime").ToString()) & "</div>")
            Else
                sb.Append("<div class='info err'>✗ Query returned no row.</div>")
            End If
            reader.Close()
            conn.Close()
        Catch ex As SqlException
            sb.Append("<div class='info err'>✗ SQL Error: " & HttpUtility.HtmlEncode(ex.Message) & "</div>")
            sb.Append("<div class='info'>Number: " & ex.Number.ToString() & "</div>")
            Try
                If Global.RGBC_Forecast.db.conn.State = ConnectionState.Open Then Global.RGBC_Forecast.db.conn.Close()
            Catch
            End Try
        Catch ex As Exception
            sb.Append("<div class='info err'>✗ Error: " & HttpUtility.HtmlEncode(ex.Message) & "</div>")
            sb.Append("<div class='info'>" & HttpUtility.HtmlEncode(ex.StackTrace) & "</div>")
            Try
                If Global.RGBC_Forecast.db.conn.State = ConnectionState.Open Then Global.RGBC_Forecast.db.conn.Close()
            Catch
            End Try
        End Try

        ' 2. Test mstUser table exists and show count (helps confirm login table)
        Try
            Dim drCount = Global.RGBC_Forecast.db.getRow("SELECT COUNT(*) AS Cnt FROM mstUser")
            If drCount IsNot Nothing Then
                sb.Append("<div class='info'>mstUser table: " & drCount("Cnt").ToString() & " user(s).</div>")
            End If
        Catch ex As Exception
            sb.Append("<div class='info err'>mstUser check: " & HttpUtility.HtmlEncode(ex.Message) & "</div>")
        End Try

        ' 3. Show current Windows identity (same as login uses)
        Try
            Dim winUser As String = Request.LogonUserIdentity.Name
            sb.Append("<div class='info'>Your Windows login (used for access): " & HttpUtility.HtmlEncode(winUser) & "</div>")
        Catch ex As Exception
            sb.Append("<div class='info'>Windows identity: " & HttpUtility.HtmlEncode(ex.Message) & "</div>")
        End Try

        phResult.Controls.Add(New LiteralControl(sb.ToString()))
    End Sub
End Class
