Imports System.Data.SqlClient
Imports CrystalDecisions.CrystalReports.Engine
Imports ReportingClass

Public Class SendApplication
    Inherits System.Web.UI.Page

    Property cid = 0

    Private Sub Me_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then

            Dim appId = Logic.Conversion.ToInteger(Request.Params("id"))

            Dim contractId = 0
            Using connection As New SqlConnection(Logic.Database.connectionString)
                connection.Open()
                Dim cmd As New SqlCommand("SELECT ClientId FROM web_DriverApplication WHERE id=@appId", connection)
                cmd.Parameters.AddWithValue("appId", appId)
                contractId = cmd.ExecuteScalar()
            End Using
            Master.CurrentClient.VerifyContractAccess(contractId)

            Dim perms = Master.CurrentClient.Permissions
            If Not perms.Contains("View Applications Page") Then Throw New HttpException(403, "Forbidden")

            Dim UseDPQ = False
            Using connection As New SqlConnection(Logic.Database.connectionString)
                connection.Open()
                Dim cmd As New SqlCommand(
                    "SELECT UsesDPQ 
                    FROM web_DriverApplication app LEFT JOIN ServiceContract c ON c.id=app.clientId 
                    WHERE app.id=@appId",
                    connection)
                cmd.Parameters.AddWithValue("appId", appId)
                UseDPQ = Logic.Conversion.ToBoolean(cmd.ExecuteScalar())
            End Using

            _LoadForm(appId)
            Master.SetParentPage("Recruiting.aspx?cid=" & cid)

        End If
    End Sub

    Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
        _SafeReturn()
    End Sub

    Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click

        Dim hasSelection = chkBundle.Checked Or chkAppReview.Checked Or chkSPH.Checked Or chkMVR.Checked _
            Or chkSubstanceTest.Checked Or chkPSP.Checked Or chkCriminalBackgroundDatabase.Checked
        If Not hasSelection Then
            phRequired.Visible = True
            Exit Sub
        End If

        Try
            Using connection As New SqlConnection(Logic.Database.connectionString)
                connection.Open()
                Using transaction = connection.BeginTransaction()
                    Dim requestId = _SaveData(connection, transaction)
                    Dim doc = _SaveDocument(requestId, connection, transaction)
                    _SendEmail(requestId, doc, connection, transaction)
                    transaction.Commit()
                End Using
            End Using

        Catch ex As Exception
            Dim errorId = Logic.Error.Log(ex)
            Response.Redirect("/Error.aspx?id=" & errorId)
        End Try

        Response.Redirect("Recruiting.aspx?cid=" & cid)
    End Sub

#Region "Internals"

    Private Sub _LoadForm(appId As Integer)
        Try
            Dim account = Master.CurrentClient
            txtRequestorName.Text = account.nameFull
            With New Logic.DriverApplicationSummary(appId)
                litId.Text = .id
                litSubmitted.Text = .dateSubmitted
                litName.Text = .applicantName
                cid = .contractId
            End With
        Catch ex As Exception
            Dim errorId = Logic.Error.Log(ex)
            Response.Redirect("/Error.aspx?id=" & errorId)
        End Try
    End Sub

    Private Sub _SafeReturn()

        ' Magic...  true if other is same origin as this website
        Dim isSameOrigin = Function(other As String) As Boolean
            Return 0 = Uri.Compare(Request.Url, New Uri(other),
                UriComponents.SchemeAndServer, UriFormat.SafeUnescaped, StringComparison.Ordinal)
        End Function

        ' Redirect, if valid
        Dim destination = Request.Params("return")
        If Not String.IsNullOrEmpty(destination) AndAlso isSameOrigin(destination) Then
            Response.Redirect(destination)
        End If

        ' On fail, just return to Default
        Response.Redirect("Default.aspx")

    End Sub

    Private Function _SaveData(connection As SqlConnection, transaction As SqlTransaction) As Integer
        Dim username = "[Web: " + Master.CurrentClient.username & "]"
        With New Logic.DriverApplicationSummary(litId.Text)
            .status = "in review"
            .Update(username, connection, transaction, resubmit:=True, allowEmail:=False)
            cid = .contractId
        End With
        With New Logic.SupportServicesRequest()
            .clientAccountId = Master.CurrentClient.id
            .applicationId = litId.Text
            .requestorName = txtRequestorName.Text
            .requestorTitle = txtRequestorTitle.Text
            .requestorSignatureId = signature.SignatureId
            .optionBundle1 = chkBundle.Checked
            .optionAppReview = chkAppReview.Checked
            .optionSPH = chkSPH.Checked
            .optionMVR = chkMVR.Checked
            .optionSubstanceTest = chkSubstanceTest.Checked
            .optionPSP = chkPSP.Checked
            .optionCriminalBackgroundDatabase = chkCriminalBackgroundDatabase.Checked
            .Submit(connection, transaction)
            Return .id
        End With
    End Function

    Private Function _SaveDocument(requestId As Integer, connection As SqlConnection, transaction As SqlTransaction) As Byte()
        Dim ReportDataSet As New dsAppSendApplication
        Dim ReportTableAdapter As New TransactionalAppSendApplicationTableAdapter
        ReportTableAdapter.SetConnection(connection, transaction)
        
        Using Report As New crptAppSendApplication
            ReportTableAdapter.Fill(ReportDataSet.AppSendApplication, requestId)
            Report.SetDataSource(ReportDataSet)

            Dim PictureBox As PictureObject = Report.ReportDefinition.ReportObjects("picSig")
            Dim LinkedFormula As FormulaFieldDefinition = Report.DataDefinition.FormulaFields("pathSig")
            Dim SignatureId = Logic.Conversion.ToInteger(ReportDataSet.AppSendApplication.Rows(0)("requestorSignatureId"))
            Reporting.SetPictureToSignature(PictureBox, LinkedFormula, SignatureId, 5600)

            Dim rawData = Reporting.StreamToByteArray(Report)

            Dim cmdSave = "
                INSERT INTO web_DriverApplicationPdf (appId, pageTitle, pageFileName, pdfData, pdfDataSize)
                VALUES (@appId, @pageTitle, @pageFileName, @pdfData, @pdfDataSize);"
            Dim cmd As New SqlCommand(cmdSave, connection, transaction)
            cmd.Parameters.AddWithValue("appId", litId.Text)
            cmd.Parameters.AddWithValue("pageTitle", "Support Services Request")
            cmd.Parameters.AddWithValue("pageFileName", "client/sendapplication.aspx")
            cmd.Parameters.AddWithValue("pdfData", rawData)
            cmd.Parameters.AddWithValue("pdfDataSize", rawData.Length)
            cmd.ExecuteNonQuery()

            Return rawData

        End Using

    End Function

    Private Sub _SendEmail(requestId As Integer, rawData As Byte(), connection As SqlConnection, transaction As SqlTransaction)

        Dim cmdGet As New SqlCommand(
            "SELECT SC.id AS ContractId, Cust.Name AS CustomerName, RequestorName, RequestorTitle, 
                App.id AS AppId, app.ApplicantNameFirst, app.ApplicantNameMiddle, app.ApplicantNameLast, app.ApplicantNameSuffix
            FROM web_SupportServicesRequest Req
            LEFT JOIN web_DriverApplication App ON App.id=Req.applicationId
            LEFT JOIN web_ClientAccount ClientAcct ON ClientAcct.id=Req.ClientAccountId
            LEFT JOIN ServiceContract SC ON SC.id=App.ClientId
            LEFT JOIN Customer Cust ON Cust.id=SC.CustomerID
            WHERE Req.id=@requestId",
            connection, transaction)
        cmdGet.Parameters.AddWithValue("requestId", requestId)

        Dim ContractId As Integer
        Dim CustomerName As String
        Dim RequestorName As String
        Dim RequestorTitle As String
        Dim AppId As Integer
        Dim ApplicantName As String
        Using dReader = cmdGet.ExecuteReader()
            dReader.Read()
            ContractId = CInt(dReader(0))
            CustomerName = CStr(dReader(1))
            RequestorName = CStr(dReader(2))
            RequestorTitle = CStr(dReader(3))
            AppId = CInt(dReader(4))
            ApplicantName = CStr(dReader(5)) & " " & CStr(dReader(6)) & " " & CStr(dReader(7)) & " " & CStr(dReader(8))
        End Using
        
        Dim email As New Logic.AutomationServer_EmailsSent() With {
            .EmailTo = My.Settings.emailStatusUpdates,
            .EmailSubject = "Application Received from Client",
            .EmailAttachmentName = "SupportServicesRequest.pdf",
            .EmailAttachmentData = rawData,
            .EmailAttachmentLength = rawData.Length}
        email.EmailBody = 
            "A support services request has been received from a client." & vbCrLf & vbCrLf &
            "Client: " & CustomerName & " - " & ContractId & vbCrLf &
            "Requested by: " & RequestorName & ", Title: " & RequestorTitle & vbCrLf &
            "Driver Applicant: #" & AppId & " - " & ApplicantName & vbCrLf & vbCrLf &
            "See attachment for more details." & vbCrLf
        email.Create(connection, transaction)

    End Sub

#End Region

End Class
