Imports RGBC_ScoreCard.SystemFunctions
Imports RGBC_ScoreCard.ProjectFunctions
Imports RGBC_ScoreCard.db

Public Class ScoreCard
   Inherits System.Web.UI.Page
    Dim strUserName As String = ""
    Dim strRepName As String = ""
    Dim intRepID As Integer = 0
    Dim intRSMAnswered As Integer = 0
   Dim strQuestionnaire As String
   Dim questionnaireID As Integer
   Dim dr As DataRow
   Public db As New db
   Private arrQuestions As New Collection()
   Private SurveyID = 0

    Protected Sub page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        
      Page.MasterPageFile = setMasterPage(Request)
    End Sub

   Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim userCheck As Integer
        Dim strDateAnswered As String = ""
        Dim strCusNoAnswered As String = ""
        
      Dim intScoreAnswered As Integer = 0
        Dim userScoreCardSecurityGroup As Integer = 0
        Dim radioSelection As RadioButtonList

        Try
            If Session.Item("User") Is Nothing Then 'lame
                LogginUser(Request, Session)
            End If

            strQuestionnaire = "Sales Person Scorecard"             'Set questionnaire name

            dr = db.getRow("SELECT QuestionnaireID FROM scrQuestionnaire WHERE strQuestionnaire ='" & strQuestionnaire & "'")   'Get QuestionnaireID
            questionnaireID = dr!QuestionnaireID
            IsNothing(dr)

            If Request.QueryString("SurveyID") <> "" Then
                SurveyID = Request.QueryString("SurveyID")
            Else
                SurveyID = 0
            End If

            If Not Me.IsPostBack Then
                If SurveyID <> 0 Then
                    'Load survey
                    dr = db.getRow("SELECT CONVERT(varchar(10), dwfScoreCard.dtDate, 120) AS dtDate, mstUser.strUserName, dwfScoreCard.UserID, dwfScoreCard.RepID, dwfScoreCard.strCustomerNo" & _
                                   " , mstUser.refUserGroupScoreCardID, Sum(dwfScoreCard.intAnswer) AS SumOfintAnswer,  mstRep.strRepName FROM dwfScoreCard INNER JOIN mstUser ON dwfScoreCard.UserID = mstUser.UserID " & _
                                   " INNER JOIN mstRep ON dwfScoreCard.RepID = mstRep.RepID WHERE dwfScoreCard.SurveyID = " & SurveyID & " GROUP BY dwfScoreCard.dtDate,  mstUser.strUserName, dwfScoreCard.UserID" & _
                                   " , dwfScoreCard.RepID, dwfScoreCard.strCustomerNo, mstUser.refUserGroupScoreCardID, mstRep.strRepName")

                    strUserName = dr!strUserName
                    intRSMAnswered = nz(dr!UserID, 0)
                    strRepName = dr!strRepName
                    intRepID = nz(dr!RepID, 0)
                    strDateAnswered = Left(dr!dtDate.ToString(), 10)
                    userScoreCardSecurityGroup = dr!refUserGroupScoreCardID
                    strCusNoAnswered = dr!strCustomerNo
                    intScoreAnswered = dr!SumOfintAnswer

                    strDate.Text = strDateAnswered
                    strDate.BorderStyle = BorderStyle.None
                    strDate.BackColor = Drawing.Color.White
                    strDate.Style.Add("text-align", "left")

                    strScore.Text = ((intScoreAnswered / 100) * 100).ToString() + "/100"
                    strScore.BorderStyle = BorderStyle.None
                    strScore.BackColor = Drawing.Color.White
                    strScore.Style.Add("text-align", "left")

                    'If strSPerson.ToString() <> "" Then
                    '    strSalesPerson.SelectedValue = strSPerson
                    '    strSalesPerson.Enabled = False
                    '    strSalesPerson.BackColor = Drawing.Color.LightGray
                    'Else
                    '    strSalesPerson.SelectedValue = 0
                    '    strSalesPerson.Enabled = True
                    'End If

                    'If userScoreCardSecurityGroup = 4 Then
                    '    strRSM.SelectedValue = strRSMAnswered
                    '    strRSM.Enabled = False
                    '    strRSM.BackColor = Drawing.Color.LightGray
                    'Else
                    '    strRSM.SelectedValue = 0
                    '    strRSM.Enabled = True
                    'End If

                    strStore.Text = strCusNoAnswered
                    strStore.ReadOnly = True
                    strStore.BorderStyle = BorderStyle.None
                    strStore.Style.Add("text-align", "left")


                    'If strStore.Text <> "" Then
                    '    strStore.ReadOnly = True
                    '    strStore.BackColor = Drawing.Color.LightGray
                    'Else
                    '    strStore.ReadOnly = False
                    'End If

                    reQuestions.DataSource = sdsAnswereds
                    reQuestions.DataBind()
                Else
                    'New survey
                    strDate.Text = DateTime.Today.ToString("yyyy-MM-dd")    'Add current date of survey to date textbox
                    strScore.Text = "/100"

                    dr = db.getRow("SELECT QuestionnaireID FROM scrQuestionnaire WHERE strQuestionnaire ='" & strQuestionnaire & "'")   'Get QuestionnaireID
                    questionnaireID = dr!QuestionnaireID

                    dr = db.getRow("SELECT refUserGroupScoreCardID FROM mstUser WHERE UserID =" & Session.Item("USERID"))   'Check to see if logged in user is a RSM 
                    userCheck = dr!refUserGroupScoreCardID

                    If userCheck = 4 Then   'Check to see if logged in user is a RSM then default set them on survey page
                        strRSM.SelectedValue = Session.Item("USERID")
                    End If

                    reQuestions.DataSource = sdsQuestions
                    reQuestions.DataBind()
                End If
            Else
                'Dim repItem As RepeaterItem
                'Dim radioSelection As RadioButtonList
                Dim strScoreV As String
                Dim intScoreV As Integer
                Dim intScoreT As Integer = 0

                For Each repItem In reQuestions.Items
                    radioSelection = repItem.FindControl("radOptions")
                    If radioSelection.SelectedValue <> "" Then
                        strScoreV = radioSelection.SelectedValue
                        intScoreV = Convert.ToInt32(strScoreV)
                        intScoreT += intScoreV
                    End If
                Next

                If intScoreT > 0 Then
                    strScore.Text = ((intScoreT / 100) * 100).ToString() + "%"
                Else
                    strScore.Text = "/100"
                End If
            End If

        Catch ex As Exception
            lblMessage.Text = ex.Message & "<BR/>" & ex.StackTrace
            SurveyID = 0
        Finally
        End Try

    End Sub

   Private Sub Page_PreRenderComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRenderComplete
      Dim imgLoading As WebControls.Image
      imgLoading = Page.Master.FindControl("imgLoading")
      imgLoading.CssClass = "invisible"
   End Sub

   Protected Sub strStore_TextChanged(sender As Object, e As EventArgs) Handles strStore.TextChanged
      Dim dr As DataRow

      Try
         dr = db.getRow("SELECT * FROM dwdCustomer WHERE blnActive = 1 And strCustomerNo = '" & db.CleanString(strStore.Text) & "' ")

         If Not dr Is Nothing Then
            lblCustomerDetails.Text = "- Customer: " & dr!strCustomerName & "<br> - Channel Segment: " & dr!strChannelPrimary & " > " & dr!strChannelSecondary & " > " & dr!strSegmentPrimary & " > " & dr!strSegmentSecondary & "<br> - Rep: " & dr!strRepName & " (" & dr!refRepID & ")"
         Else
            lblCustomerDetails.Text = "WARNING! Customer not found!"
         End If

      Catch ex As Exception
         lblMessage.Text = ex.Message & "<BR/>" & ex.StackTrace
      Finally
      End Try
   End Sub

   Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
      Dim repItem As RepeaterItem

      Try
         Dim radioSelection As RadioButtonList
         Dim hiddenQID As HiddenField
         Dim txtComments As TextBox
         Dim lblQuestion, lblOrder, lblCat As Label
         Dim intQID, intOrder, intAnswer As Integer
            Dim strCategory, order, strQuestion, strComments As String

            If SurveyID <> 0 Then

                'UPDATE scrSurvey table ~ replaced Session.Item("USERID") with rsm
                RGBC_ScoreCard.db.doQuery("UPDATE scrSurvey SET strLastEdit = getDate() WHERE SurveyID=" & SurveyID)

                'Loop through Repeater Items
                For Each repItem In reQuestions.Items
                    'SurveyID = 2
                    hiddenQID = repItem.FindControl("QuestionID")       'Get QuestionID from repeaterItem
                    intQID = Convert.ToInt32(hiddenQID.Value)

                    lblCat = repItem.FindControl("strCategory")         'Get strCategory from repeaterItem
                    strCategory = lblCat.Text
                    strCategory = db.CleanString(strCategory.ToString()).Trim()

                    lblOrder = repItem.FindControl("intOrder")          'Get intOrder from repeaterItem
                    order = lblOrder.Text.Substring(1)
                    intOrder = Convert.ToInt32(order)

                    lblQuestion = repItem.FindControl("strQuestion")    'Get strQuestion from repeaterItem
                    strQuestion = lblQuestion.Text
                    strQuestion = strQuestion.Replace("<BR/>", vbCrLf)
                    strQuestion = strQuestion.Replace("'", "''")
                    strQuestion = db.CleanString(strQuestion.ToString()).Trim()

                    txtComments = repItem.FindControl("txtComments")    'Get txtComments from repeaterItem
                    strComments = txtComments.Text
                    strComments = db.CleanString(strComments.ToString()).Trim()

                    radioSelection = repItem.FindControl("radOptions")
                    intAnswer = Convert.ToInt32(radioSelection.SelectedValue)

                    '~ replaced Session.Item("USERID") with strrsm.selectedV
                    RGBC_ScoreCard.db.doQuery(" UPDATE dwfScoreCard SET intAnswer=" & intAnswer & ", txtComments='" & strComments & "', strLastUser='" & Session.Item("USERNAME") & "' WHERE SurveyID=" & SurveyID & " AND QuestionID=" & intQID & " ")
                Next
            Else
                'INSERT INTO scrSurvey table ~ CONVERT(varchar(10), scrSurvey.dtDate, 120) ~ removed Session.Item("USERID") for UserID
                RGBC_ScoreCard.db.doQuery("INSERT INTO scrSurvey(dtDate, UserID, QuestionnaireID, RepID, strCustomerNo) " & _
                                       " VALUES ( CONVERT(varchar(10),GETDATE(), 120) , " & strRSM.SelectedValue & ", " & questionnaireID & ", '" & strSalesPerson.SelectedValue & "','" & strStore.Text & "')")

                'GET last ID from scrSurvey table
                dr = db.getRow("SELECT MAX(SurveyID) As SurveyID FROM scrSurvey")
                Dim newSurveyID As Integer = dr!SurveyID
                IsNothing(dr)
                'dr.Delete()

                'Loop through Repeater Items
                For Each repItem In reQuestions.Items
                    'SurveyID = 2
                    hiddenQID = repItem.FindControl("QuestionID")       'Get QuestionID from repeaterItem
                    intQID = Convert.ToInt32(hiddenQID.Value)

                    lblCat = repItem.FindControl("strCategory")         'Get strCategory from repeaterItem
                    strCategory = lblCat.Text
                    strCategory = db.CleanString(strCategory.ToString()).Trim()

                    lblOrder = repItem.FindControl("intOrder")          'Get intOrder from repeaterItem
                    order = lblOrder.Text.Substring(1)
                    intOrder = Convert.ToInt32(order)

                    lblQuestion = repItem.FindControl("strQuestion")    'Get strQuestion from repeaterItem
                    strQuestion = lblQuestion.Text
                    strQuestion = strQuestion.Replace("<BR/>", vbCrLf)
                    strQuestion = strQuestion.Replace("'", "''")
                    strQuestion = db.CleanString(strQuestion.ToString()).Trim()

                    txtComments = repItem.FindControl("txtComments")    'Get txtComments from repeaterItem
                    strComments = txtComments.Text
                    strComments = db.CleanString(strComments.ToString()).Trim()

                    radioSelection = repItem.FindControl("radOptions")  'Get Selected radio buttons from repeaterItem
                    intAnswer = Convert.ToInt32(radioSelection.SelectedValue)

                    '~ replaced Session.Item("USERID") with RSM.selectedV
                    RGBC_ScoreCard.db.doQuery("INSERT INTO dwfScoreCard(SurveyID, dtDate, UserID, QuestionnaireID, RepID, strCustomerNo, strQuestionnaire, QuestionID, strQuestion, strCategory, strOptionType, intOrder, blnComments, intAnswer, txtComments, strLastUser) " & _
                                              " VALUES (" & newSurveyID & ",CONVERT(varchar(10),GETDATE(), 120), " & strRSM.SelectedValue & ", " & questionnaireID & ", '" & strSalesPerson.SelectedValue & "','" & strStore.Text & "','" & strQuestionnaire & "' " & _
                                              " ," & intQID & ",'" & strQuestion & "','" & strCategory & "','Range10'," & intOrder & "," & 1 & "," & intAnswer & ",'" & strComments & "','" & Session.Item("USERNAME") & "')")

                Next
            End If
            lblMessageQuestions.Text = "Save Successful!"
            Response.Redirect("Home.aspx?surveyCheck=True")

        Catch ex As Exception
            lblMessageQuestions.Text = ex.Message & "<BR/>" & ex.StackTrace
        Finally
        End Try
    End Sub

    Protected Sub FormatRepeaterRow(sender As Object, e As RepeaterItemEventArgs)
        Dim radioSelection As RadioButtonList
        Dim dvr As DataRowView

        If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then

            radioSelection = e.Item.FindControl("radOptions")
            dvr = e.Item.DataItem

            If Convert.ToInt32(dvr("intAnswer") > 0) Then
                radioSelection.SelectedValue = dvr("intAnswer")
            Else
                radioSelection.SelectedValue = "0"
            End If
        End If

    End Sub


   Public Function myFunc(ByVal val As String) As String
      If val = "" Then
         Return DBNull.Value.ToString()
      Else
         Return val
      End If
   End Function

    Protected Sub strRSM_SelectedIndexChanged(sender As Object, e As EventArgs) Handles strRSM.SelectedIndexChanged
        
    End Sub

    Protected Sub strSalesPerson_DataBinding(sender As Object, e As EventArgs) Handles strSalesPerson.DataBinding

    End Sub

    Protected Sub strRSM_DataBound(sender As Object, e As EventArgs) Handles strRSM.DataBound

        If SurveyID <> 0 Then
            If Not IsNothing(strRSM.Items.FindByValue(intRSMAnswered)) Then
                strRSM.SelectedValue = intRSMAnswered
            Else
                strRSM.Items.Add(New ListItem(strUserName, intRSMAnswered))
                strRSM.SelectedValue = intRSMAnswered
            End If
            strRSM.Enabled = False
        End If
    End Sub

    Protected Sub strSalesPerson_DataBound(sender As Object, e As EventArgs) Handles strSalesPerson.DataBound

        If SurveyID <> 0 Then
            If Not IsNothing(strSalesPerson.Items.FindByValue(intRepID)) Then
                strSalesPerson.SelectedValue = intRepID
            Else
                strSalesPerson.Items.Add(New ListItem(strRepName, intRepID))
                strSalesPerson.SelectedValue = intRepID
            End If
            strSalesPerson.Enabled = False
        End If
    End Sub

    Protected Sub strSalesPerson_SelectedIndexChanged(sender As Object, e As EventArgs) Handles strSalesPerson.SelectedIndexChanged
        Dim dr As DataRow

        If strSalesPerson.SelectedValue <> 0 Then
            Try
                dr = db.getRow("SELECT Max(scrSurvey.dtDate) AS dtDate FROM scrSurvey WHERE scrSurvey.RepID =" & strSalesPerson.SelectedValue)

                If IsNothing(dr!dtDate) Or IsDBNull(dr!dtDate) Then
                    lblLastDate.Visible = True
                    lblDate.Visible = True
                    lblDate.Text = "None done before."
                Else
                    lblLastDate.Visible = True
                    lblDate.Visible = True
                    lblDate.Text = "" & dr!dtDate
                End If

            Catch ex As Exception
                lblMessage.Text = ex.Message & "<BR/>" & ex.StackTrace
            Finally
            End Try
        Else
            lblLastDate.Visible = False
            lblDate.Visible = False
        End If
    End Sub
End Class