Imports System.Data.SqlClient
Imports System.Threading

Public Class EditContract
    Inherits System.Web.UI.Page

    Property contractId As Integer
    Property parentId As Integer

    Protected Sub Page_Load() Handles Me.Load
        Try

            contractId = Logic.Conversion.ToInteger(Request.Params("id"))

            If contractId = 0 Then
                parentId = Logic.Conversion.ToInteger(Request.Params("cid"))
            Else
                Using connection As New SqlConnection(Logic.Database.connectionString)
                    connection.Open()
                    Dim cmd As New SqlCommand(
                        "SELECT c.OwnerContractId
                        FROM ServiceContract sc
                        LEFT JOIN Customer c ON c.ID=sc.CustomerID
                        WHERE sc.ID=@contractId", connection)
                    cmd.Parameters.AddWithValue("contractId", contractId)
                    parentId = cmd.ExecuteScalar()
                End Using
            End If
            Master.CurrentClient.VerifyContractOrAgencyAccess(parentId)

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

            If Not Page.IsPostBack Then
                Master.SetParentPage("Contracts.aspx?cid=" & parentId)
                _FillData()
            End If

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

    Private Sub btnCancel_Click() Handles btnCancel.Click
        Response.Redirect("Contracts.aspx?cid=" & parentId)
    End Sub

    Private Sub btnSave_Click() Handles btnSave.Click
        Using connection As New SqlConnection(Logic.Database.connectionString)
            connection.Open()

            Dim cmd As New SqlCommand("", connection)
            cmd.Parameters.AddWithValue("accountId", Master.CurrentClient.id)
            cmd.Parameters.AddWithValue("modifiedBy", "[Web: " & Master.CurrentClient.username & "]")
            cmd.Parameters.AddWithValue("parentId", parentId)
            cmd.Parameters.AddWithValue("contractId", contractId)
            cmd.Parameters.AddWithValue("name", txtName.Text)
            cmd.Parameters.AddWithValue("status", If(chkActive.Checked, "Active", "InActive"))
            cmd.Parameters.AddWithValue("isInActive", Not chkActive.Checked)

            If contractId = 0 Then
                cmd.CommandText =
                    "INSERT INTO Customer (
                        name,address1,address2,city,state,zip,phone1,phone2,fax,email,website,
                        primaryContact,primaryContactPhone1,primaryContactPhone2,primaryContactFax,primaryContactEmail,primaryContactAddress,primaryContactCity,primaryContactState,primaryContactZip,
                        secondaryContact,secondaryContactPhone1,secondaryContactPhone2,secondaryContactFax,secondaryContactEmail,secondaryContactAddress,secondaryContactCity,secondaryContactState,secondaryContactZip,
                        DOTNumber,Notes,InActive,IFTAApplicable,HASMAT,passengerCarrier,
                        enteredBy,enteredDate,editedBy,editedDate,ownerContractId)
                    VALUES (
                        @name,'','','','','','','','','','',
                        '','','','','','','','','',
                        '','','','','','','','','',
                        '','',@isInActive,0,0,0,
                        @modifiedBy,GETDATE(),@modifiedBy,GETDATE(),@parentId);
                    INSERT INTO ServiceContract (
                        customerID,contractDate,billPeriodId,billAmount,contractManagerId,
                        billTo,address1,address2,city,state,zip,phone1,phone2,fax,email,
                        primaryContact,primaryContactPhone1,primaryContactPhone2,primaryContactFax,primaryContactEmail,primaryContactAddress,primaryContactCity,primaryContactState,primaryContactZip,
                        secondaryContact,secondaryContactPhone1,secondaryContactPhone2,secondaryContactFax,secondaryContactEmail,secondaryContactAddress,secondaryContactCity,secondaryContactState,secondaryContactZip,
                        status,enteredDate,enteredBy,editedDate,editedBy,
                        dername,derphone,deremail)
                    VALUES (
                        @@IDENTITY,GETDATE(),5,0,-1,
                        '','','','','','','','','','',
                        '','','','','','','','','',
                        '','','','','','','','','',
                        @status,GETDATE(),@modifiedBy,GETDATE(),@modifiedBy,
                        '','','')
                    SELECT @@IDENTITY;"
                contractId = cmd.ExecuteScalar()
            Else
                ' If we add more fields, maybe use hidden fields to check if
                ' customer is updated. For now, we won't worry about it.
                cmd.CommandText =
                    "UPDATE Customer SET InActive=@isInActive,name=@name,editedBy=@modifiedBy,editedDate=GETDATE()
                        WHERE ID=(SELECT CustomerID FROM ServiceContract WHERE ID=@contractId);
                    UPDATE ServiceContract SET Status=@status,editedBy=@modifiedBy,editedDate=GETDATE()
                        WHERE ID=@contractId"
                cmd.ExecuteNonQuery()
            End If

            cmd.CommandText =
                "DELETE FROM web_ClientContractsMap
                    WHERE clientId=@accountId AND contractId=@contractId;
                INSERT INTO web_ClientContractsMap (clientId,contractId)
                    VALUES (@accountId,@contractId);"
            cmd.Parameters("contractId").Value = contractId
            cmd.ExecuteNonQuery()
        End Using

        Response.Redirect("Contracts.aspx?cid=" & parentId)
    End Sub
    
    Private Sub _FillData()
        Using connection As New SqlConnection(Logic.Database.connectionString)
            connection.Open()
            Dim cmd As New SqlCommand(
                "SELECT sc.status,c.Name
                FROM ServiceContract sc LEFT JOIN Customer c ON c.ID=sc.CustomerID
                WHERE sc.ID=@contractId", connection)
            cmd.Parameters.AddWithValue("contractId", contractId)
            
            Dim dReader = cmd.ExecuteReader()
            If Not dReader.Read() Then Exit Sub

            txtName.Text = dReader("Name")
            hidOldName.Value = dReader("Name")
            chkActive.Checked = (dReader("Status") = "Active")
            hidOldActive.Value = (dReader("Status") = "Active")

        End Using
    End Sub

End Class