<cfparam name="form.Status" default="0">
<cfparam name="form.M1041_INFLNZ" default="">
<cfparam name="form.M1046_INFLNZ_RECD_CRNT_SEASON" default="">
<cfparam name="form.M1051_PVX_RCVD_AGNCY" default="">
<cfparam name="form.M1056_PVX_RSN_NOT_RCVD_AGNCY" default="">
<cfparam name="form.clinical_authorization" default="0">
<cfparam name="form.case_authorization" default="0">
<cfparam name="form.agreed_careplan" default="0">
<cfparam name="form.Caregiver" default="">
<cfparam name="form.problem_Intake" default="">
<cfparam name="form.Caregiver_competency" default="">
<cfparam name="form.Caregiver_commitment" default="">
<cfparam name="form.admitid" default="0">
<cfparam name="form.Advance_Directive" default="">
<cfparam name="form.otherAdvance_Directive" default="">
<cfparam name="form.otherMD_Homebound" default="">
<cfparam name="form.drafts" default="0">
<cfparam name="form.admitaction" default="">
<cfset isAdmissionDraft = (form.admitaction EQ 'admissiondrafts' OR form.drafts EQ 1)>
<cfparam name="form.Agy_Admit" default="">
<cfparam name="cookie.AutoAdmitSvcs_ID" default="0">
<cfparam name="form.M0102_PHYSN_ORDRD_SOCROC_DT_NA" default="0">
<cfparam name="form.M1100_PTNT_LVG_STUTN" default="">
<cfset form.Record_Creation_Date = "#Now()#" />
<cfset form.Record_Created_By = 0 />
<cfset form.Record_Mod_Date = #Now()# />
<cfset form.Record_Mod_By = 0 />
<cfset DoCommit = 1>
<!--- Read logged-in employee ID from session; never overwrite session.employeeid here --->
<cfset admissionEmployeeId = 0 />
<cfif structKeyExists(session, "EmployeeId") AND val(session.EmployeeId) GT 0>
    <cfset admissionEmployeeId = val(session.EmployeeId) />
<cfelseif structKeyExists(session, "EmployeeID") AND val(session.EmployeeID) GT 0>
    <cfset admissionEmployeeId = val(session.EmployeeID) />
<cfelseif structKeyExists(session, "ULoginID") AND val(session.ULoginID) GT 0>
    <cfset admissionEmployeeId = val(session.ULoginID) />
</cfif>

<!--- Safeguard: Validate integer form fields that might contain PLACEHOLDER --->
<cfparam name="form.Referral_ID" default="0">
<cfif NOT IsNumeric(form.Referral_ID) OR UCase(Trim(form.Referral_ID)) EQ "PLACEHOLDER" OR Trim(form.Referral_ID) EQ "">
    <cfset form.Referral_ID = 0>
<cfelse>
    <cfset form.Referral_ID = Val(form.Referral_ID)>
</cfif>

<cfparam name="form.Refer_Phys_ID" default="0">
<cfif NOT IsNumeric(form.Refer_Phys_ID) OR UCase(Trim(form.Refer_Phys_ID)) EQ "PLACEHOLDER" OR Trim(form.Refer_Phys_ID) EQ "">
    <cfset form.Refer_Phys_ID = 0>
<cfelse>
    <cfset form.Refer_Phys_ID = Val(form.Refer_Phys_ID)>
</cfif>

<cfparam name="form.Render_Phys_ID" default="0">
<cfif NOT IsNumeric(form.Render_Phys_ID) OR UCase(Trim(form.Render_Phys_ID)) EQ "PLACEHOLDER" OR Trim(form.Render_Phys_ID) EQ "">
    <cfset form.Render_Phys_ID = 0>
<cfelse>
    <cfset form.Render_Phys_ID = Val(form.Render_Phys_ID)>
</cfif>

<cfparam name="form.Clinical_Manager" default="0">
<cfif NOT IsNumeric(form.Clinical_Manager) OR UCase(Trim(form.Clinical_Manager)) EQ "PLACEHOLDER" OR Trim(form.Clinical_Manager) EQ "">
    <cfset form.Clinical_Manager = 0>
<cfelse>
    <cfset form.Clinical_Manager = Val(form.Clinical_Manager)>
</cfif>

<cfparam name="form.Case_Manager" default="0">
<cfif NOT IsNumeric(form.Case_Manager) OR UCase(Trim(form.Case_Manager)) EQ "PLACEHOLDER" OR Trim(form.Case_Manager) EQ "">
    <cfset form.Case_Manager = 0>
<cfelse>
    <cfset form.Case_Manager = Val(form.Case_Manager)>
</cfif>

<cfparam name="form.Admission_Source" default="">
<cfif NOT isAdmissionDraft AND form.Status NEQ 2 AND (Trim(form.Admission_Source) EQ "" OR UCase(Trim(form.Admission_Source)) EQ "PLACEHOLDER")>
    <cfset enc_patient_id = encrypt(form.ID, application.enckey, "AES", "Hex") />
    <cfset session.required_fields_error = "Source of Admission must be updated by office staff and cannot be saved as PLACEHOLDER." />
    <cfif form.admitid NEQ 0>
        <cfset enc_admit_id = encrypt(form.admitid, application.enckey, "AES", "Hex") />
        <cflocation url="#application.secure#/patientadmin_new/index.cfm?page=patient&ID=#enc_patient_id#&admitid=#enc_admit_id#&cat=newadmission_form&required_fields_redirect=1" addtoken="no">
    <cfelse>
        <cflocation url="#application.secure#/patientadmin_new/index.cfm?page=patient&ID=#enc_patient_id#&admitid=0&cat=newadmission_form&required_fields_redirect=1" addtoken="no">
    </cfif>
</cfif>

<cfif form.Advance_Directive EQ '' OR UCase(Trim(form.Advance_Directive)) EQ 'PLACEHOLDER'>
    <cfif Len(Trim(form.otherAdvance_Directive)) GT 0>
        <cfset form.Advance_Directive = form.otherAdvance_Directive />
    </cfif>
</cfif>

<cfif form.admitid EQ 0>  
<cftransaction>
    <cftry>
        <cfquery  name="getadmit" datasource="#Application.DataSrc#">
                   SELECT IFNULL(MAX(Admit_ID),0)+1 As pAdmit_ID FROM #Request.prefix_db_agency#.pAdmit 
        </cfquery>
        <cfset pAdmit_ID =  #getadmit.pAdmit_ID# />
       <cfcatch>
            <cfset DoCommit = 0>
            <cftransaction action="rollback" />
        </cfcatch>
    </cftry>
    <cfif DoCommit EQ 1>
        <cftransaction action="commit" />
    </cfif>            
 </cftransaction>
<cfelseif isAdmissionDraft>
   <cfset pAdmit_ID = form.admitid />
<cfelse>
   <cftransaction>
     <cftry>
        <cfquery name="update_pAdmit" datasource="#Application.DataSrc#"  result="result">
           UPDATE #Request.prefix_db_agency#.pAdmit SET 
           Status   = <cfqueryparam VALUE="2"  cfsqltype="cf_sql_integer">,      
           Date_Change = <cfqueryparam VALUE="#form.Record_Mod_Date#"  cfsqltype="cf_sql_timestamp">,
           Change_by = <cfqueryparam VALUE="#form.Record_Mod_By#"  cfsqltype="cf_sql_integer">
           WHERE  Patient_ID = <cfqueryparam VALUE="#form.ID#"  cfsqltype="cf_sql_integer">
           AND Admit_ID = <cfqueryparam VALUE="#form.admitid#"  cfsqltype="cf_sql_integer">
        </cfquery>
        <cfset pAdmit_ID =  #form.admitid# />
        <cfcatch>
            <cfset DoCommit = 0>
            <cftransaction action="rollback" />
        </cfcatch>
    </cftry>
    <cfif DoCommit EQ 1>
        <cftransaction action="commit" />
    </cfif>            
</cftransaction>
</cfif>


<cfif form.Status EQ 2>
    <cfquery  name="getoasis" datasource="#Application.DataSrc#">
        SELECT  *  FROM #Request.prefix_db_agency#.pAssessments
        WHERE Patient_ID =  <cfqueryparam VALUE="#form.ID#"  cfsqltype="cf_sql_integer">
        AND  Admit_ID = <cfqueryparam VALUE="#form.admitid#"  cfsqltype="cf_sql_integer">
        AND  Status =  <cfqueryparam VALUE="0"  cfsqltype="cf_sql_integer">
    </cfquery>
    <cfquery  name="updatepAdmit_Svcs" datasource="#Application.DataSrc#">
        UPDATE #Request.prefix_db_agency#.pAdmit_Svcs
            SET   Status    =  <cfqueryparam value = "2" CFSQLType ="CF_SQL_INTEGER"> 
        WHERE Admit_ID = <cfqueryparam VALUE="#form.admitid#"  cfsqltype="cf_sql_integer">
    </cfquery>
    <cfif getoasis.recordcount gt 0 >
        <cfset assesment_ids = ValueList(getoasis.Assmt_ID) />
        <cfquery  name="DELETE_Assessments" datasource="#Application.DataSrc#">
            UPDATE #Request.prefix_db_agency#.pAssessments 
            SET Status =  <cfqueryparam VALUE="2"  cfsqltype="cf_sql_integer">
            WHERE Assmt_ID IN  (<cfqueryparam VALUE="#assesment_ids#"  cfsqltype="cf_sql_integer" list="yes">)
            AND Status = 0
        </cfquery>
        <cfquery  name="DELETE_pScheduless" datasource="#Application.DataSrc#">
            UPDATE #Request.prefix_db_agency#.pSchedules 
            SET Status =  <cfqueryparam VALUE="2"  cfsqltype="cf_sql_integer">
            WHERE Assmt_ID IN  (<cfqueryparam VALUE="#assesment_ids#"  cfsqltype="cf_sql_integer" list="yes">)
            AND Status = 0
        </cfquery>
         <cfquery  name="DELETE_pProblem" datasource="#Application.DataSrc#">
            UPDATE #Request.prefix_db_agency#.pProblem 
            SET Status =  <cfqueryparam VALUE="2"  cfsqltype="cf_sql_integer">
            WHERE Assmt_ID IN  (<cfqueryparam VALUE="#assesment_ids#"  cfsqltype="cf_sql_integer" list="yes">)
            AND Status = 0
        </cfquery>
        <cfquery  name="DELETE_pCareplan" datasource="#Application.DataSrc#">
            UPDATE #Request.prefix_db_agency#.pCareplan 
            SET Status =  <cfqueryparam VALUE="2"  cfsqltype="cf_sql_integer">
            WHERE Assmt_ID IN  (<cfqueryparam VALUE="#assesment_ids#"  cfsqltype="cf_sql_integer" list="yes">)
            AND Status = 0
        </cfquery>
         <cfquery  name="DELETE_pAuths" datasource="#Application.DataSrc#">
            UPDATE #Request.prefix_db_agency#.pAuths 
            SET Status =  <cfqueryparam VALUE="2"  cfsqltype="cf_sql_integer">
            WHERE Assmt_ID IN  (<cfqueryparam VALUE="#assesment_ids#"  cfsqltype="cf_sql_integer" list="yes">)
            AND Status = 0
        </cfquery>
        <cfquery  name="DELETE_pProgress" datasource="#Application.DataSrc#">
            UPDATE #Request.prefix_db_agency#.pProgress 
            SET Status =  <cfqueryparam VALUE="2"  cfsqltype="cf_sql_integer">
            WHERE Assmt_ID IN  (<cfqueryparam VALUE="#assesment_ids#"  cfsqltype="cf_sql_integer" list="yes">)
            AND Status = 0
        </cfquery>
        <cfquery  name="DELETE_pOASIS_QA" datasource="#Application.DataSrc#">
            DELETE FROM #Request.prefix_db_agency#.pOASIS_QA 
            WHERE Assmt_ID IN  (<cfqueryparam VALUE="#assesment_ids#"  cfsqltype="cf_sql_integer" list="yes">)
        </cfquery>
         <cfquery  name="DELETE_pCMS4857" datasource="#Application.DataSrc#">
            UPDATE #Request.prefix_db_agency#.pCMS4857 
            SET Status =  <cfqueryparam VALUE="2"  cfsqltype="cf_sql_integer">
            WHERE Assmt_ID IN  (<cfqueryparam VALUE="#assesment_ids#"  cfsqltype="cf_sql_integer" list="yes">)
            AND Status = 0
        </cfquery>
    </cfif>

<cfelse>

    <cfquery  name="getSOC" datasource="#Application.DataSrc#">
        SELECT  *  FROM #Request.prefix_db_agency#.pAssessments
        WHERE Patient_ID =  <cfqueryparam VALUE="#form.ID#"  cfsqltype="cf_sql_integer">
        AND  Status =  <cfqueryparam VALUE="0"  cfsqltype="cf_sql_integer">
        AND  F26 like '1%'
    </cfquery>

    <cfif form.admitid NEQ 0 AND isAdmissionDraft>
    <cfquery name="UpdatingpAdmit" datasource="#Application.DataSrc#" result="result">
       UPDATE #Request.prefix_db_agency#.pAdmit SET
            Status = <cfqueryparam VALUE="#form.Status#" cfsqltype="cf_sql_integer">,
            Admit_Type = <cfqueryparam VALUE="#form.Admit_Type#" cfsqltype="cf_sql_varchar">,
            Referral_ID = <cfqueryparam VALUE="#Val(form.Referral_ID)#" cfsqltype="cf_sql_integer">,
            Admission_Source = <cfqueryparam VALUE="#form.Admission_Source#" cfsqltype="cf_sql_varchar">,
            M0104_PHYSN_RFRL_DT = <cfqueryparam VALUE="#form.M0104_PHYSN_RFRL_DT#" cfsqltype="cf_sql_date" null="#form.M0104_PHYSN_RFRL_DT EQ ''#">,
            Refer_Phys_ID = <cfqueryparam VALUE="#Val(form.Refer_Phys_ID)#" cfsqltype="cf_sql_integer">,
            <cfif form.M0102_PHYSN_ORDRD_SOCROC_DT NEQ ''>
            M0102_PHYSN_ORDRD_SOCROC_DT = <cfqueryparam VALUE="#form.M0102_PHYSN_ORDRD_SOCROC_DT#" cfsqltype="cf_sql_date">,
            M0102_PHYSN_ORDRD_SOCROC_DT_NA = <cfqueryparam VALUE="0" cfsqltype="cf_sql_integer">,
            <cfelse>
            M0102_PHYSN_ORDRD_SOCROC_DT = NULL,
            M0102_PHYSN_ORDRD_SOCROC_DT_NA = <cfqueryparam VALUE="#form.M0102_PHYSN_ORDRD_SOCROC_DT_NA#" cfsqltype="cf_sql_integer">,
            </cfif>
            M0030_START_CARE_DT = <cfqueryparam VALUE="#form.M0030_START_CARE_DT#" cfsqltype="cf_sql_date" null="#form.M0030_START_CARE_DT EQ ''#">,
            Render_Phys_ID = <cfqueryparam VALUE="#Val(form.Render_Phys_ID)#" cfsqltype="cf_sql_integer">,
            Date_F2F = <cfqueryparam VALUE="#form.Date_F2F#" cfsqltype="cf_sql_date" null="#form.Date_F2F EQ ''#">,
            MD_Clinical_Condition = <cfqueryparam VALUE="#form.MD_Clinical_Condition#" cfsqltype="cf_sql_varchar">,
            MD_Homebound = <cfqueryparam VALUE="#form.otherMD_Homebound#" cfsqltype="cf_sql_varchar">,
            Caregiver = <cfqueryparam VALUE="#form.Caregiver#" cfsqltype="cf_sql_varchar">,
            M1100_PTNT_LVG_STUTN = <cfqueryparam VALUE="#form.M1100_PTNT_LVG_STUTN#" cfsqltype="cf_sql_varchar">,
            Service_Place = <cfqueryparam VALUE="#form.Service_Place#" cfsqltype="cf_sql_varchar">,
            FU_Freq = <cfqueryparam VALUE="#form.FU_Freq#" cfsqltype="cf_sql_varchar">,
            Clinical_Manager = <cfqueryparam VALUE="#Val(form.Clinical_Manager)#" cfsqltype="cf_sql_integer">,
            clinical_authorization = <cfqueryparam VALUE="#form.clinical_authorization#" cfsqltype="cf_sql_integer">,
            Case_Manager = <cfqueryparam VALUE="#Val(form.Case_Manager)#" cfsqltype="cf_sql_integer">,
            case_authorization = <cfqueryparam VALUE="#form.case_authorization#" cfsqltype="cf_sql_integer">,
            agreed_careplan = <cfqueryparam VALUE="#form.agreed_careplan#" cfsqltype="cf_sql_integer">,
            Advance_Directive = <cfqueryparam VALUE="#form.Advance_Directive#" cfsqltype="cf_sql_varchar">,
            Advance_DirectiveDate = <cfqueryparam VALUE="#form.Advance_DirectiveDate#" cfsqltype="cf_sql_date" null="#form.Advance_DirectiveDate EQ ''#">,
            Code_Status = <cfqueryparam VALUE="#form.Code_Status#" cfsqltype="cf_sql_varchar">,
            Emerg_Priority = <cfqueryparam VALUE="#form.Emerg_Priority#" cfsqltype="cf_sql_varchar">,
            problem_Intake = <cfqueryparam VALUE="#form.problem_Intake#" cfsqltype="cf_sql_varchar">,
            Caregiver_competency = <cfqueryparam VALUE="#form.Caregiver_competency#" cfsqltype="cf_sql_varchar">,
            Caregiver_commitment = <cfqueryparam VALUE="#form.Caregiver_commitment#" cfsqltype="cf_sql_varchar">,
            Notes = <cfqueryparam VALUE="#form.Notes#" cfsqltype="cf_sql_varchar">,
            Approved = <cfqueryparam VALUE="Yes" cfsqltype="cf_sql_varchar">,
            drafts = <cfqueryparam VALUE="1" cfsqltype="cf_sql_integer">,
            Agy_Admit = <cfqueryparam VALUE="#form.Agy_Admit#" cfsqltype="cf_sql_date" null="#form.Agy_Admit EQ ''#">,
            Date_Change = <cfqueryparam VALUE="#now()#" cfsqltype="cf_sql_timestamp">,
            Change_by = <cfqueryparam VALUE="#admissionEmployeeId#" cfsqltype="cf_sql_integer">
       WHERE Patient_ID = <cfqueryparam VALUE="#form.ID#" cfsqltype="cf_sql_integer">
       AND Admit_ID = <cfqueryparam VALUE="#pAdmit_ID#" cfsqltype="cf_sql_integer">
       AND Status = <cfqueryparam VALUE="0" cfsqltype="cf_sql_integer">
    </cfquery>
    <cfelse>
    <cfquery name="InsertingpAdmit"  datasource="#Application.DataSrc#"  result="result">
       INSERT INTO #Request.prefix_db_agency#.pAdmit (
            Admit_ID,Patient_ID, Status, Admit_Type, Referral_ID, Admission_Source, M0104_PHYSN_RFRL_DT, Refer_Phys_ID,
             <cfif form.M0102_PHYSN_ORDRD_SOCROC_DT NEQ ''>M0102_PHYSN_ORDRD_SOCROC_DT,<cfelse>M0102_PHYSN_ORDRD_SOCROC_DT_NA,</cfif><cfif form.M0030_START_CARE_DT NEQ ''>M0030_START_CARE_DT,</cfif>  Render_Phys_ID, Date_F2F, MD_Clinical_Condition, MD_Homebound, 
            Caregiver, <!--- Nursing, Therapy, Aide, ---> M1100_PTNT_LVG_STUTN, Service_Place,FU_Freq, Clinical_Manager,clinical_authorization, Case_Manager, case_authorization,agreed_careplan,
             Advance_Directive, <cfif form.Advance_DirectiveDate NEQ ''>Advance_DirectiveDate,</cfif> Code_Status,
              Emerg_Priority, problem_Intake, Caregiver_competency, Caregiver_commitment, Notes, Approved,
              <cfif form.admitaction EQ 'admissiondrafts' OR form.drafts EQ 1>drafts,</cfif>
              <cfif form.Agy_Admit NEQ ''>Agy_Admit,</cfif>
               Date_Create, Created_by, Date_Change, Change_by
            )
        VALUES
        ( 
          <cfqueryparam VALUE="#pAdmit_ID#"  cfsqltype="cf_sql_integer">,
          <cfqueryparam VALUE="#form.ID#"  cfsqltype="cf_sql_integer">,
          <cfqueryparam VALUE="#form.Status#"  cfsqltype="cf_sql_integer">,
          <cfqueryparam VALUE="#form.Admit_Type#"  cfsqltype="cf_sql_varchar">,
          <cfqueryparam VALUE="#Val(form.Referral_ID)#"  cfsqltype="cf_sql_integer">,
          <cfqueryparam VALUE="#form.Admission_Source#"  cfsqltype="cf_sql_varchar">,
          <cfif form.M0104_PHYSN_RFRL_DT NEQ ''>
             <cfqueryparam VALUE="#form.M0104_PHYSN_RFRL_DT#"  cfsqltype="cf_sql_date">,
           <cfelse>
              NULL,
           </cfif>
          <cfqueryparam VALUE="#Val(form.Refer_Phys_ID)#"  cfsqltype="cf_sql_integer">,
          <cfif form.M0102_PHYSN_ORDRD_SOCROC_DT NEQ ''>
                <cfqueryparam VALUE="#form.M0102_PHYSN_ORDRD_SOCROC_DT#"  cfsqltype="cf_sql_date">,
          <cfelse>
             <cfqueryparam VALUE="#form.M0102_PHYSN_ORDRD_SOCROC_DT_NA#"  cfsqltype="cf_sql_integer">,
          </cfif>
           <cfif form.M0030_START_CARE_DT NEQ ''>
                <cfqueryparam VALUE="#form.M0030_START_CARE_DT#"  cfsqltype="cf_sql_date">,
           </cfif>
          <cfqueryparam VALUE="#Val(form.Render_Phys_ID)#"  cfsqltype="cf_sql_integer">,
          <cfif form.Date_F2F NEQ ''>
            <cfqueryparam VALUE="#form.Date_F2F#"  cfsqltype="cf_sql_date">,
          <cfelse>
             NULL,
          </cfif>
          <cfqueryparam VALUE="#form.MD_Clinical_Condition#"  cfsqltype="cf_sql_varchar">,
          <cfqueryparam VALUE="#form.otherMD_Homebound#"  cfsqltype="cf_sql_varchar">,
          <cfqueryparam VALUE="#form.Caregiver#"  cfsqltype="cf_sql_varchar">,
          <!--- <cfqueryparam VALUE="#form.Nursing#"  cfsqltype="cf_sql_varchar">,
          <cfqueryparam VALUE="#form.Therapy#"  cfsqltype="cf_sql_varchar">,
          <cfqueryparam VALUE="#form.Aide#"  cfsqltype="cf_sql_varchar">, --->
          <cfqueryparam VALUE="#form.M1100_PTNT_LVG_STUTN#"  cfsqltype="cf_sql_varchar">,
          <cfqueryparam VALUE="#form.Service_Place#"  cfsqltype="cf_sql_varchar">,
           <cfqueryparam VALUE="#form.FU_Freq#"  cfsqltype="cf_sql_varchar">,
          <cfqueryparam VALUE="#Val(form.Clinical_Manager)#"  cfsqltype="cf_sql_integer">,
          <cfqueryparam VALUE="#form.clinical_authorization#"  cfsqltype="cf_sql_integer">,
          <cfqueryparam VALUE="#Val(form.Case_Manager)#"  cfsqltype="cf_sql_integer">,
          <cfqueryparam VALUE="#form.case_authorization#"  cfsqltype="cf_sql_integer">,
          <cfqueryparam VALUE="#form.agreed_careplan#"  cfsqltype="cf_sql_integer">,
          <cfqueryparam VALUE="#form.Advance_Directive#"  cfsqltype="cf_sql_varchar">,
          <cfif form.Advance_DirectiveDate NEQ ''>
            <cfqueryparam VALUE="#form.Advance_DirectiveDate#"  cfsqltype="cf_sql_date">,
          </cfif>
          <cfqueryparam VALUE="#form.Code_Status#"  cfsqltype="cf_sql_varchar">,
          <cfqueryparam VALUE="#form.Emerg_Priority#"  cfsqltype="cf_sql_varchar">,
          <cfqueryparam VALUE="#form.problem_Intake#"  cfsqltype="cf_sql_varchar">,
          <cfqueryparam VALUE="#form.Caregiver_competency#"  cfsqltype="cf_sql_varchar">,
          <cfqueryparam VALUE="#form.Caregiver_commitment#"  cfsqltype="cf_sql_varchar">,
          <cfqueryparam VALUE="#form.Notes#"  cfsqltype="cf_sql_varchar">,
          <cfif form.admitaction EQ 'QA'>
            <cfqueryparam VALUE="Not paired"  cfsqltype="cf_sql_varchar">,
          <cfelse>
            <cfqueryparam VALUE="Yes"  cfsqltype="cf_sql_varchar">,
          </cfif>
          <cfif form.admitaction EQ 'admissiondrafts' OR form.drafts EQ 1>
            <cfqueryparam VALUE="1"  cfsqltype="cf_sql_integer">,
           </cfif>
          <cfif form.Agy_Admit NEQ ''>
            <cfqueryparam VALUE="#form.Agy_Admit#"  cfsqltype="cf_sql_date">,
          </cfif>

          <cfqueryparam VALUE="#form.Record_Creation_Date#"  cfsqltype="cf_sql_timestamp">,
          <cfqueryparam VALUE="#admissionEmployeeId#"  cfsqltype="cf_sql_integer">,
          <cfqueryparam VALUE="#form.Record_Creation_Date#"  cfsqltype="cf_sql_timestamp">,
          <cfqueryparam VALUE="#admissionEmployeeId#"  cfsqltype="cf_sql_integer">
        )
    </cfquery>
    </cfif>
    <cfif cookie.AutoAdmitSvcs_ID NEQ 0 >
            <cfquery  name="updatepAdmit_Svcs" datasource="#Application.DataSrc#">
                UPDATE #Request.prefix_db_agency#.pAdmit_Svcs
                    SET 
                    Admit_ID    =  <cfqueryparam value = "#pAdmit_ID#" CFSQLType ="CF_SQL_INTEGER"> ,
                    Date_Change = <cfqueryparam value="#now()#" cfsqltype="cf_sql_timestamp">,
                    Change_by   = <cfqueryparam value = "#admissionEmployeeId#" CFSQLType ="CF_SQL_INTEGER"> 
                WHERE AutoAdmitSvcs_ID  IN (<cfqueryparam VALUE="#cookie.AutoAdmitSvcs_ID#"  cfsqltype="cf_sql_integer" list="yes">)
                AND Status = 0
            </cfquery> 
            <cfset cookie.AutoAdmitSvcs_ID = 0> 
    </cfif>
    <!--- Operational SOC for assessments/scheduling: EMR admit date when set, else physician M0030 --->
    <cfset request.pat = createObject("component", "components.general.patients").init() />
    <cfset operationalSOCDate = "" />
    <cfif form.Agy_Admit NEQ '' AND IsDate(form.Agy_Admit)>
        <cfset operationalSOCDate = form.Agy_Admit />
    <cfelseif form.M0030_START_CARE_DT NEQ '' AND IsDate(form.M0030_START_CARE_DT)>
        <cfset operationalSOCDate = form.M0030_START_CARE_DT />
    </cfif>
    <!--- When EMR admit differs from physician SOC, assessment dates are managed separately --->
    <cfset emrAdmitDiffersFromPhysicianSOC = false />
    <cfif form.Agy_Admit NEQ '' AND IsDate(form.Agy_Admit) AND form.M0030_START_CARE_DT NEQ '' AND IsDate(form.M0030_START_CARE_DT) AND DateCompare(form.Agy_Admit, form.M0030_START_CARE_DT) NEQ 0>
        <cfset emrAdmitDiffersFromPhysicianSOC = true />
    </cfif>
    <cfset donot_create_oasis =  'no' />
    <cfif form.admitaction EQ 'no_order' OR form.admitaction EQ '487order' OR form.admitaction EQ 'admissiondrafts'>
        <cfquery  name="getadmit_services" datasource="#Application.DataSrc#">
            SELECT * FROM #Request.prefix_db_agency#.pAdmit_Svcs
            WHERE   Admit_ID    =  <cfqueryparam value = "#pAdmit_ID#" CFSQLType ="CF_SQL_INTEGER"> 
            AND Status = 0
            AND Assmt_ID = 0
        </cfquery>
        <cfif getadmit_services.recordcount EQ 0 >
             <cfset donot_create_oasis =  'yes' />
        </cfif>
    </cfif>

    <cfif CGI.REMOTE_ADDR EQ '103.143.7.161'>
        <cfdump var ="#donot_create_oasis#">
    </cfif>

    <cfif (<!--- form.admitid EQ 0 OR ---> form.admitaction EQ 'sendfax'
             OR form.admitaction EQ 'update' OR  form.admitaction EQ '487order' 
              OR form.admitaction EQ 'admissiondrafts' OR form.admitaction EQ 'no_order' ) AND donot_create_oasis EQ 'no'  >  
       
        <cfquery datasource="#Application.DataSrc#" name="GetPatient">
            SELECT pPatients.*,Agency.* ,pAdmit.Refer_Phys_ID AS Primary_ReferringPhys_Id_M0072,
            pAdmit.*
            FROM   #Request.prefix_db_agency#.pPatients
            JOIN  #Request.prefix_db_agency#.pAdmit ON  pAdmit.Patient_Id =  pPatients.Patient_Id 
            JOIN  #Request.prefix_db_lookup#.Agency ON  Agency.Agency_Id = pPatients.Loc_ID
            WHERE  pPatients.Patient_Id =  <cfqueryparam value = "#form.ID#" CFSQLType ="CF_SQL_INTEGER">
            AND pAdmit.Admit_ID =  <cfqueryparam value = "#pAdmit_ID#" CFSQLType ="CF_SQL_INTEGER">
            AND pPatients.status < 2
            AND  pAdmit.status = 0
            GROUP BY pPatients.Patient_Id        
        </cfquery>
        <cfquery datasource="#Application.DataSrc#" name="GetPatPayer">
            SELECT * FROM #Request.prefix_db_agency#.pPtPayer 
            WHERE Patient_ID = '#form.ID#'
            AND Status = 0 
        </cfquery>


        <cfquery  name="getSOCSN_Svcs" datasource="#Application.DataSrc#">
            SELECT * FROM #Request.prefix_db_agency#.pAdmit_Svcs
            WHERE   Admit_ID    =  <cfqueryparam value = "#pAdmit_ID#" CFSQLType ="CF_SQL_INTEGER"> 
            <!--- AND Skill like '1%' --->
            AND Status = 0
        </cfquery>

        <cfset Request.Order_description =   "" />
        <cfif getSOCSN_Svcs.recordcount EQ 0 >
            <cfquery  name="pAdmit_Svcs_insert" datasource="#Application.DataSrc#">
                INSERT INTO #Request.prefix_db_agency#.pAdmit_Svcs
                (
                       Admit_ID,Patient_ID, Status, Skill,
                       <cfif GetPatient.M0030_START_CARE_DT NEQ ''> 
                                Start_Date,
                       </cfif>
                        Physician_order, Notes, Admitted,
                        Date_Create, Created_by, Date_Change, Change_by
                ) 
                VALUES
                (
                    '#pAdmit_ID#' ,'#form.ID#',0, '1 - SOC - SN', 
                    <cfif GetPatient.M0030_START_CARE_DT NEQ ''> 
                        '#DateFormat(GetPatient.M0030_START_CARE_DT,"yyyy-mm-dd")#',
                    </cfif>
                    'yes','Created  1 - SOC - SN by admission','yes',
                     #now()# , #admissionEmployeeId#  , #now()#, #admissionEmployeeId# 
                )                                   
            </cfquery>
        </cfif> 

        <cfquery  name="getpAdmit_Svcs" datasource="#Application.DataSrc#">
            SELECT * FROM #Request.prefix_db_agency#.pAdmit_Svcs
            WHERE   Admit_ID    =  <cfqueryparam value = "#pAdmit_ID#" CFSQLType ="CF_SQL_INTEGER"> 
            AND Status = 0
            AND Skill NOT IN ('0')
        </cfquery>

        <cfscript>
            request.pat = CreateObject("component","components.general.patients").init();
            GetM = request.pat.medslist(#form.ID#);
        </cfscript>
        <cfquery dbtype="query" name="GetMeds">
            SELECT * FROM GetM
            WHERE Status = 0 
            AND N0415 IS NOT NULL
        </cfquery>
        <cfquery dbtype="query" name="GetN0415">
            SELECT * FROM GetM
            WHERE Status = 0 
            AND N0415 IS  NULL
        </cfquery>
        <cfset N0415_list = #ValueList(GetMeds.N0415)# />
        <cfset F206 = '0. No' />
        <cfset F207 = '0. No' />
        <cfset F208 = '0. No' />
        <cfset F209 = '0. No' />
        <cfset F210 = '0. No' />
        <cfset F211 = '0. No' />
        <cfset F212 = '0. No' />
        <cfset F213 = '0. No' />
        <cfset F214 = '0. No' />
        <cfset F215 = '0. No' />
        <cfset F216 = '0. No' />
        <cfset F217 = '0. No' />
        <cfif GetN0415.recordcount gt 0 >
          <cfset F220 = 'Not Applicable' />
        <cfelse>
          <cfset F220 = '' />
        </cfif>
        <cfif N0415_list contains '3'>
          <cfset F206 = '1. Yes' />
          <cfset F207 = '1. Yes' />
        </cfif>
        <cfif N0415_list contains '4'>
          <cfset F208 = '1. Yes' />
          <cfset F209 = '1. Yes' />
        </cfif>
        <cfif N0415_list contains '1'>
          <cfset F210 = '1. Yes' />
          <cfset F211 = '1. Yes' />
        </cfif>
        <cfif N0415_list contains '6'>
          <cfset F212 = '1. Yes' />
          <cfset F213 = '1. Yes' />
        </cfif>
        <cfif N0415_list contains '5'>
          <cfset F214 = '1. Yes' />
          <cfset F215 = '1. Yes' />
        </cfif>
        <cfif N0415_list contains '2'>
          <cfset F216 = '1. Yes' />
          <cfset F217 = '1. Yes' />
        </cfif>
        <cfif  form.admitaction EQ 'sendfax' OR form.admitaction EQ '487order'>
            <cfset Request.Order_description =   'Physician Face-to-Face Date: ' & #DateFormat(form.Date_F2F,"mm/dd/yyyy")# & '<br>' />
            <cfset Request.Order_description =   Request.Order_description & 'Clinical Condition Requiring Home Care per Certifying Physician: ' & #form.MD_Clinical_Condition# & '<br>' />
            <cfset Request.Order_description =   Request.Order_description & 'Homebound Status per Certifying Physician: ' &  #form.otherMD_Homebound# & '<br>' />
        </cfif>

        <cfset Request.Assmt_ID  =  0 >
        <cfset F26 =  '' />
        <cfset F27 =  '' />
        <cfloop query="getpAdmit_Svcs">
            <cfset skillLower = LCase(Trim(Skill)) />
            <cfif skillLower EQ '1 - soc - sn'>
                <cfset F26 =  '1 - Start of care - further visits planned' />
                <cfset F27 =  'SN' />
            <cfelseif skillLower EQ '1 - soc - pt'>
                <cfset F26 =  '1 - Start of care - further visits planned - Physical Therapy' />
                <cfset F27 =  'PT' />
            <cfelseif skillLower EQ '1 - soc - ot'>
                <cfset F26 =  '1 - Start of care - further visits planned - Occupational Therapy' />
                <cfset F27 =  'OT' />
            <cfelseif skillLower EQ '3 - roc - sn'>
                <cfset F26 =  '3 - Resumption of care (after inpatient stay)' />
                <cfset F27 =  'SN' />
            <cfelseif skillLower EQ '3 - roc - pt'>
                <cfset F26 =  '3 - Resumption of care (after inpatient stay)' />
                <cfset F27 =  'PT' />
            <cfelseif skillLower EQ '4 - recertification sn' OR skillLower EQ '4 - recertification'>
                <cfset F26 =  '4 - Recertification (follow-up) reassessment' />
                <cfset F27 =  'SN' />
            <cfelseif skillLower EQ '4 - recertification pt'>
                <cfset F26 =  '4 - Recertification (follow-up) reassessment - PT' />
                <cfset F27 =  'PT' />
            <cfelseif skillLower EQ '4 - recertification ot'>
                <cfset F26 =  '4 - Recertification (follow-up) reassessment - OT' />
                <cfset F27 =  'OT' />            
            <cfelseif skillLower EQ 'pt eval'>
                <cfset F26 =  'PT Adult Evaluation' />
                <cfset F27 =  'PT' />
            <cfelseif skillLower EQ 'ot eval'>
                <cfset F26 =  'OT Adult Evaluation' />
                <cfset F27 =  'OT' />
            <cfelseif skillLower EQ 'msw eval'>
                <cfset F26 =  'MSW Evaluation' />
                <cfset F27 =  'MSW' />
            <cfelseif skillLower EQ 'st eval'>
                <cfset F26 =  'ST Adult Evaluation' />
                <cfset F27 =  'ST' />
            <cfelseif skillLower EQ 'sn eval'>
                <cfset F26 =  'SN Adult Evaluation' />
                <cfset F27 =  'SN' />
            <cfelseif skillLower EQ 'hospice comprehensive'>
                <cfset F26 =  'Hospice Comprehensive' />
                <cfset F27 =  'SN' />
            <cfelseif skillLower EQ 'hospice admission'>
                <cfset F26 =  'Hospice admission' />
                <cfset F27 =  'SN' />
            <cfelseif skillLower EQ 'sn pediatric evaluation'>
                <cfset F26 =  'SN Pediatric Evaluation' />
                <cfset F27 =  'SN' />
            <cfelseif skillLower EQ 'pt pediatric evaluation'>
                <cfset F26 =  'PT Pediatric Evaluation' />
                <cfset F27 =  'PT' />
            <cfelseif skillLower EQ 'ot pediatric evaluation'>
                <cfset F26 =  'OT Pediatric Evaluation' />
                <cfset F27 =  'OT' />
            <cfelseif skillLower EQ 'st pediatric evaluation'>
                <cfset F26 =  'ST Pediatric Evaluation' />
                <cfset F27 =  'ST' />
            <cfelseif skillLower EQ 'palliative'>
                <cfset F26 =  'Palliative' />
                <cfset F27 =  'SN' />
            </cfif>
            <cfset certstartdate = #now()#>
            <cfset certPeriodDays = 59 />
            <cfif form.Admit_Type EQ 'Hospice'>
                <cfset certPeriodDays = 89 />
            </cfif>
            <cfset certenddate = dateAdd('d', certPeriodDays, certstartdate) />
            <cfif operationalSOCDate NEQ '' AND Left(F26, 1) EQ '1'>
                <cfset certstartdate = operationalSOCDate />
                <cfset certenddate = dateAdd('d', certPeriodDays, certstartdate) />
            <cfelseif getpAdmit_Svcs.Start_Date NEQ ''>
                <cfset certstartdate = getpAdmit_Svcs.Start_Date />
                <cfset certenddate = dateAdd('d', certPeriodDays, certstartdate) />
            </cfif>
            <cfquery  name="getOASIS" datasource="#Application.DataSrc#">
               SELECT  *  FROM  #Request.prefix_db_agency#.pAssessments
               WHERE Status = 0 
               AND  F26 = <cfqueryparam cfsqltype="cf_sql_varchar" value="#F26#">
               AND F27  =  <cfqueryparam cfsqltype="cf_sql_varchar" value="#F27#">
               AND Admit_ID  =  <cfqueryparam cfsqltype="cf_sql_integer" value="#pAdmit_ID#">
            </cfquery>
            <cfset isAdultEvaluation = (FindNoCase('Adult Evaluation', F26) GT 0 AND FindNoCase('follow-up', F26) EQ 0) />
            <cfif  #Left(F26,1)# EQ 1 AND getOASIS.recordcount GT 0>
                <cfset Request.Assmt_ID = #getOASIS.Assmt_ID# />
            </cfif>

            <cfif getOASIS.recordcount gt 0 AND NOT isAdultEvaluation AND Left(F26, 1) EQ '1' AND operationalSOCDate NEQ '' AND NOT emrAdmitDiffersFromPhysicianSOC>
                    <cfset socAssessmentEndDate = dateAdd('d', certPeriodDays, operationalSOCDate) />
                    <cfquery  name="updatepassessments" datasource="#Application.DataSrc#">
                        UPDATE #Request.prefix_db_agency#.pAssessments
                            SET
                            F176 = <cfqueryparam value="#operationalSOCDate#" cfsqltype="CF_SQL_DATE">,
                            F177 = <cfqueryparam value="#operationalSOCDate#" cfsqltype="CF_SQL_DATE">,
                            F178 = <cfqueryparam value="#socAssessmentEndDate#" cfsqltype="CF_SQL_DATE">,
                            Record_Mod_Date = <cfqueryparam value="#now()#" cfsqltype="cf_sql_timestamp">,
                            Record_Mod_By = <cfqueryparam value="#admissionEmployeeId#" CFSQLType="CF_SQL_INTEGER">
                        WHERE Assmt_ID = <cfqueryparam CFSQLType="CF_SQL_INTEGER" value="#getOASIS.Assmt_ID#">
                        AND Admit_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#pAdmit_ID#">
                        AND status = 0
                    </cfquery>
                    <cfquery name="updateSocAdmitSvcsStartDate" datasource="#Application.DataSrc#">
                        UPDATE #Request.prefix_db_agency#.pAdmit_Svcs
                        SET Start_Date = <cfqueryparam value="#operationalSOCDate#" cfsqltype="CF_SQL_DATE">,
                            Date_Change = <cfqueryparam value="#now()#" cfsqltype="cf_sql_timestamp">,
                            Change_by = <cfqueryparam value="#admissionEmployeeId#" CFSQLType="CF_SQL_INTEGER">
                        WHERE AutoAdmitSvcs_ID = <cfqueryparam CFSQLType="CF_SQL_INTEGER" value="#getpAdmit_Svcs.AutoAdmitSvcs_ID#">
                        AND Admit_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#pAdmit_ID#">
                        AND Status = 0
                    </cfquery>
            </cfif>


            <cfset Request.Order_description =   Request.Order_description & Skill & " Notes: "& getpAdmit_Svcs.Notes  & "<br>"/>

              <cfif (getOASIS.recordcount eq 0 <!--- OR isAdultEvaluation --->) AND getpAdmit_Svcs.Assmt_ID EQ 0  AND F26  NEQ ''>
                <cfset duplicateF176 = "" />
                <cfif operationalSOCDate NEQ ''>
                    <cfset duplicateF176 = DateFormat(operationalSOCDate,'yyyy-mm-dd') />
                </cfif>

                <cfquery name="CheckExistingAssessment" datasource="#Application.DataSrc#">
                    SELECT Assmt_ID
                    FROM #Request.prefix_db_agency#.pAssessments
                    WHERE Status = 0
                    AND Admit_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#pAdmit_ID#">
                    AND Patient_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#session.cs.patientid#">
                    AND IFNULL(F26, '') = <cfqueryparam cfsqltype="cf_sql_varchar" value="#F26#">
                    AND IFNULL(F27, '') = <cfqueryparam cfsqltype="cf_sql_varchar" value="#F27#">
                    AND IFNULL(F176, '') = <cfqueryparam cfsqltype="cf_sql_varchar" value="#duplicateF176#">
                    ORDER BY AutoAssmt_ID ASC
                    LIMIT 1
                </cfquery>

                <cfif CheckExistingAssessment.recordcount GT 0>
                    <cfset Request.Assmt_ID = CheckExistingAssessment.Assmt_ID />
                    <cfquery name="linkExistingAssessment" datasource="#Application.DataSrc#">
                        UPDATE #Request.prefix_db_agency#.pAdmit_Svcs
                        SET Assmt_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#Request.Assmt_ID#">
                        WHERE AutoAdmitSvcs_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#getpAdmit_Svcs.AutoAdmitSvcs_ID#">
                        AND status = 0
                    </cfquery>
                <cfelse>
                    <cfquery  name="getass" datasource="#Application.DataSrc#">
			                   SELECT IFNULL(Max(Assmt_ID),0)+1 as Assmt_ID  FROM  #Request.prefix_db_agency#.pAssessments
					       WHERE Status = 0
		            </cfquery>
		            
		            <!--- Safeguard: Ensure Assmt_ID is never 0 - if it is, start from 1 --->
		            <cfif getass.Assmt_ID EQ 0>
		                <cfquery  name="getass" datasource="#Application.DataSrc#">
		                    SELECT 1 as Assmt_ID
		                </cfquery>
		                <cflog file="assessments" text="WARNING: Assmt_ID was 0, reset to 1 for agency #Request.prefix_db_agency#">
		            </cfif>
                
                <cfquery  name="Insert_assessment" datasource="#Application.DataSrc#"> 
                    INSERT INTO #Request.prefix_db_agency#.pAssessments
                    (
                        Assmt_ID,Admit_ID,Patient_ID,Loc_ID,F26,F27, <cfif operationalSOCDate NEQ ''>F176,</cfif>
                        <cfif certstartdate NEQ ''> F177,F178,</cfif>
                        <cfif LEFT(F26,1) EQ  '1'>
                            F206,F207,F208,F209,F210, F211, F212,F213,F214,F215,F216,F217,F220,
                        </cfif>
                        Record_Creation_Date,Record_Created_By, Record_Mod_Date, Record_Mod_By 
                    )  
                   VALUES
                   (
                        <cfqueryparam cfsqltype="cf_sql_integer" value="#getass.Assmt_ID#">,
                        <cfqueryparam cfsqltype="cf_sql_integer" value="#pAdmit_ID#">,
                        <cfqueryparam cfsqltype="cf_sql_integer" value="#session.cs.patientid#">,
                        <cfqueryparam cfsqltype="cf_sql_integer" value="#Val(session.AgencyId)#">,
                        <cfqueryparam cfsqltype="cf_sql_varchar" value="#F26#">,
                        <cfqueryparam cfsqltype="cf_sql_varchar" value="#F27#">,
                        <cfif operationalSOCDate NEQ ''>
                            <cfqueryparam cfsqltype="cf_sql_date" value="#DATEFORMAT(operationalSOCDate,'yyyy-mm-dd')#">,
                        </cfif>
                        <cfif certstartdate NEQ ''>
                            <cfqueryparam cfsqltype="cf_sql_date" value="#DATEFORMAT(certstartdate,'yyyy-mm-dd')#">,
                            <cfqueryparam cfsqltype="cf_sql_date" value="#DATEFORMAT(certenddate,'yyyy-mm-dd')#">,
                        </cfif>
                        <cfif LEFT(F26,1) EQ  '1'>
                            <cfqueryparam value="#F206#"  cfsqltype="cf_sql_varchar">,
                            <cfqueryparam value="#F207#"  cfsqltype="cf_sql_varchar">,
                            <cfqueryparam value="#F208#"  cfsqltype="cf_sql_varchar">,
                            <cfqueryparam value="#F209#"  cfsqltype="cf_sql_varchar">,
                            <cfqueryparam value="#F210#"  cfsqltype="cf_sql_varchar">,
                            <cfqueryparam value="#F211#"  cfsqltype="cf_sql_varchar">,
                            <cfqueryparam value="#F212#"  cfsqltype="cf_sql_varchar">,
                            <cfqueryparam value="#F213#"  cfsqltype="cf_sql_varchar">,
                            <cfqueryparam value="#F214#"  cfsqltype="cf_sql_varchar">,
                            <cfqueryparam value="#F215#"  cfsqltype="cf_sql_varchar">,
                            <cfqueryparam value="#F216#"  cfsqltype="cf_sql_varchar">,
                            <cfqueryparam value="#F217#"  cfsqltype="cf_sql_varchar">,
                            <cfqueryparam value="#F220#"  cfsqltype="cf_sql_varchar">,
                        </cfif>                                
                       <cfqueryparam VALUE="#now()#"  cfsqltype="cf_sql_timestamp">,
                        <cfqueryparam VALUE="#admissionEmployeeId#"  cfsqltype="cf_sql_integer">,
                        <cfqueryparam VALUE="#now()#"  cfsqltype="cf_sql_timestamp">,
                        <cfqueryparam VALUE="#admissionEmployeeId#"  cfsqltype="cf_sql_integer"> 
                   )
                </cfquery> 
                <cfquery datasource="#Application.DataSrc#" name="Last_Ass">
                    <cfsetting requesttimeout="5000">
                    SELECT LAST_INSERT_ID() as LastInsertID
                </cfquery>
                <cfset Request.Assmt_ID = #getass.Assmt_ID# />
                <cfquery  name="Getpats" datasource="#Application.DataSrc#">
                   SELECT * FROM #Request.prefix_db_agency#.pPatients
                   WHERE pPatients.Patient_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#session.cs.patientid#">
                   AND pPatients.Status  NOT IN (2,3) 
                </cfquery>
                <cfset certstartdate = now() />
                <cfif #Left(F26,1)# EQ 1 >
                    <cfquery  name="Insert_Coding_request" datasource="#Application.DataSrc#">
                        INSERT INTO #Request.prefix_db_lookup#.Coding_Request  (Agency_ID,Request_Date,Last_Name,First_Name,Assessment_Type,
                         Assessment_Date,Assigned_to,Coding_status,Assigned_by,Request_Time,MHCB_Entered,
                         time_requested,Updated_by) 
                        VALUES ('#session.agencyid#','#DateFormat(now(),"yyyy-mm-dd")#',
                            '#Getpats.Pt_Last#','#Getpats.Pt_First#','#F26#',
                            '#DateFormat(certstartdate,"yyyy-mm-dd")#','Melissa','H_P_Review',
                            '#admissionEmployeeId#',
                            '#TimeFormat(now(), "short")#',#now()#,#now()#,'#Session.employeeid#')
                    </cfquery>
                </cfif> 
                <cfquery  name="Insert_Coding_request" datasource="#Application.DataSrc#">
                    INSERT INTO #Request.prefix_db_lookup#.Coding_Request  (Agency_ID,Request_Date,Last_Name,First_Name,
                        Assessment_Type,
                     Assessment_Date,Assigned_to,Coding_status,Assigned_by,Request_Time,MHCB_Entered,
                     time_requested,Updated_by) 
                    VALUES ('#session.agencyid#','#DateFormat(now(),"yyyy-mm-dd")#',
                        '#Getpats.Pt_Last#','#Getpats.Pt_First#','#F26#',
                        '#DateFormat(certstartdate,"yyyy-mm-dd")#','Melissa','Coding',
                        '#admissionEmployeeId#',
                        '#TimeFormat(now(), "short")#',#now()#,#now()#,'#Session.employeeid#')
                </cfquery>


                <cfif session.agencyid NEQ '179' >    
                    <cfsavecontent variable="body_informations">
                        <cfoutput>
                            Hello Team,<br><br>
                            We got a new coding request with below information<br>
                            Agency Name   : <b>#getTimeZone.Agency_Name# (#getTimeZone.Agency_Login#)</b><br>
                            Patient Name  : <b>#Getpats.Pt_First#,#Getpats.Pt_Last#</b><br>
                            Requested Date: <b>#DateFormat(now(),"yyyy-mm-dd")# - #TimeFormat(now(), "short")#</b><br>
                            Assessment Type: <b>#F26# - #DateFormat(certstartdate,"yyyy-mm-dd")#</b><br><br><br><br>
                            <i>
                                This is an automated system notification from <a href='https://secure.myhomecarebiz.com/index.cfm'>MyHomeCareBiz.com</a>. Therefore, there is no Unsubscribe option.
                            </i>
                            <br><br><br><br><br><br>
                        </cfoutput>
                    </cfsavecontent>
                    <cfscript>
                        request.general = CreateObject("component","components.general.general").init();
                        getresult = request.general.SendMail(To="jasmin.s@myhomecarebiz.com,billing@myhomecarebiz.com,coding@myhomecarebiz.com,denise.l@myhomecarebiz.com,charmaine.v@myhomecarebiz.com,jordan.d@myhomecarebiz.com,ann.r@myhomecarebiz.com,hedelyn.f@myhomecarebiz.com,jayar.p@myhomecarebiz.com",Subject="Notification for New Coding Request",Body="'#body_informations#'");
                    </cfscript>
                </cfif>

                <cfquery  name="getOASIS" datasource="#Application.DataSrc#">
                    UPDATE  #Request.prefix_db_agency#.pAdmit_Svcs 
                    SET Assmt_ID = #Request.Assmt_ID#
                    WHERE AutoAdmitSvcs_ID = #getpAdmit_Svcs.AutoAdmitSvcs_ID# 
                    ANd status = 0
                </cfquery>
                </cfif>
            </cfif>
        </cfloop>

        <!--- #9883 - Create Hospice admission assessment when Admit_Type is 'Hospice' --->
        <cfif form.Admit_Type EQ 'Hospice'>
            <!--- Check if Hospice admission assessment already exists for this admission --->
            <cfquery  name="getHospiceAssessment" datasource="#Application.DataSrc#">
                SELECT * FROM #Request.prefix_db_agency#.pAssessments
                WHERE Admit_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#pAdmit_ID#">
                AND Patient_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#form.ID#">
                AND F26 = <cfqueryparam cfsqltype="cf_sql_varchar" value="Hospice admission">
                AND Status = 0
            </cfquery>
            
            <!--- Create Hospice admission assessment if it doesn't exist --->
            <cfif getHospiceAssessment.recordcount EQ 0>
                <cfset certstartdate = now()>
                <cfset certenddate = dateAdd('d', 59, certstartdate)>
                <cfif operationalSOCDate NEQ ''>
                    <cfset certstartdate = operationalSOCDate>
                    <cfset certenddate = dateAdd('d', 59, certstartdate)>
                </cfif>
                <cfset hospiceF176 = "" />
                <cfif operationalSOCDate NEQ ''>
                    <cfset hospiceF176 = DateFormat(operationalSOCDate,'yyyy-mm-dd') />
                </cfif>

                <cfquery name="CheckExistingHospiceAssessment" datasource="#Application.DataSrc#">
                    SELECT Assmt_ID
                    FROM #Request.prefix_db_agency#.pAssessments
                    WHERE Status = 0
                    AND Admit_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#pAdmit_ID#">
                    AND Patient_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#form.ID#">
                    AND IFNULL(F26, '') = <cfqueryparam cfsqltype="cf_sql_varchar" value="Hospice admission">
                    AND IFNULL(F27, '') = <cfqueryparam cfsqltype="cf_sql_varchar" value="SN">
                    AND IFNULL(F176, '') = <cfqueryparam cfsqltype="cf_sql_varchar" value="#hospiceF176#">
                    ORDER BY AutoAssmt_ID ASC
                    LIMIT 1
                </cfquery>

                <cfset hospiceAssmtID = 0>
                <cfif CheckExistingHospiceAssessment.recordcount GT 0>
                    <cfset hospiceAssmtID = CheckExistingHospiceAssessment.Assmt_ID>
                <cfelse>
                    <cfquery  name="getass" datasource="#Application.DataSrc#">
                        SELECT IFNULL(Max(Assmt_ID),0)+1 as Assmt_ID  FROM  #Request.prefix_db_agency#.pAssessments
                        WHERE Status = 0
                    </cfquery>
                    
                    <!--- Safeguard: Ensure Assmt_ID is never 0 - if it is, start from 1 --->
                    <cfif getass.Assmt_ID EQ 0>
                        <cfquery  name="getass" datasource="#Application.DataSrc#">
                            SELECT 1 as Assmt_ID
                        </cfquery>
                        <cflog file="assessments" text="WARNING: Assmt_ID was 0, reset to 1 for agency #Request.prefix_db_agency#">
                    </cfif>

                    <cfquery  name="Insert_hospice_assessment" datasource="#Application.DataSrc#"> 
                        INSERT INTO #Request.prefix_db_agency#.pAssessments
                        (
                            Assmt_ID,Admit_ID,Patient_ID,Loc_ID,F26,F27,
                            <cfif operationalSOCDate NEQ ''>F176,</cfif>
                            <cfif certstartdate NEQ ''>F177,F178,</cfif>
                            Record_Creation_Date,Record_Created_By, Record_Mod_Date, Record_Mod_By 
                        )  
                        VALUES
                        (
                            <cfqueryparam cfsqltype="cf_sql_integer" value="#getass.Assmt_ID#">,
                            <cfqueryparam cfsqltype="cf_sql_integer" value="#pAdmit_ID#">,
                            <cfqueryparam cfsqltype="cf_sql_integer" value="#form.ID#">,
                            <cfqueryparam cfsqltype="cf_sql_integer" value="#Val(session.AgencyId)#">,
                            <cfqueryparam cfsqltype="cf_sql_varchar" value="Hospice admission">,
                            <cfqueryparam cfsqltype="cf_sql_varchar" value="SN">,
                            <cfif operationalSOCDate NEQ ''>
                                <cfqueryparam cfsqltype="cf_sql_date" value="#DATEFORMAT(operationalSOCDate,'yyyy-mm-dd')#">,
                            </cfif>
                            <cfif certstartdate NEQ ''>
                                <cfqueryparam cfsqltype="cf_sql_date" value="#DATEFORMAT(certstartdate,'yyyy-mm-dd')#">,
                                <cfqueryparam cfsqltype="cf_sql_date" value="#DATEFORMAT(certenddate,'yyyy-mm-dd')#">,
                            </cfif>
                            <cfqueryparam VALUE="#now()#"  cfsqltype="cf_sql_timestamp">,
                            <cfqueryparam VALUE="#admissionEmployeeId#"  cfsqltype="cf_sql_integer">,
                            <cfqueryparam VALUE="#now()#"  cfsqltype="cf_sql_timestamp">,
                            <cfqueryparam VALUE="#admissionEmployeeId#"  cfsqltype="cf_sql_integer"> 
                        )
                    </cfquery>
                    <cfset hospiceAssmtID = getass.Assmt_ID>
                </cfif>
                
                <!--- Update the service to link it to the assessment if a Hospice service exists --->
                <cfquery  name="getHospiceService" datasource="#Application.DataSrc#">
                    SELECT * FROM #Request.prefix_db_agency#.pAdmit_Svcs
                    WHERE Admit_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#pAdmit_ID#">
                    AND Patient_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#form.ID#">
                    AND (Skill LIKE '%Hospice%' OR Skill = 'Hospice Comprehensive')
                    AND Status = 0
                    AND Assmt_ID = 0
                    LIMIT 1
                </cfquery>
                
                <cfif getHospiceService.recordcount GT 0>
                    <cfquery  name="updateHospiceService" datasource="#Application.DataSrc#">
                        UPDATE #Request.prefix_db_agency#.pAdmit_Svcs 
                        SET Assmt_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#hospiceAssmtID#">
                        WHERE AutoAdmitSvcs_ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#getHospiceService.AutoAdmitSvcs_ID#">
                        AND Status = 0
                    </cfquery>
                </cfif>
            </cfif>
        </cfif>

        <cfquery datasource="#Application.DataSrc#" name="GetAssessments">
            SELECT * FROM #Request.prefix_db_agency#.pAssessments
            WHERE Assmt_ID = <cfqueryparam value="#Request.Assmt_ID#" cfsqltype="CF_SQL_INTEGER">
            AND status = 0
        </cfquery>
           
        <cfif  form.admitaction EQ '487order' OR form.admitaction EQ 'sendfax' AND GetAssessments.recordcount gt 0>

                <cfquery  datasource="#Application.DataSrc#" name="AddForm">
                        INSERT INTO #Request.prefix_db_agency#.pCMS4857 
                            (
                                Assmt_ID, Status,Form_Type, Date_Sent, Insured_HIC, Date_Admit, Certification_From, 
                                Certification_To, Pt_Agy_ID, Agy_CCN, Pt_First, Pt_Last, Pt_Street, Pt_City, Pt_State,
                                Pt_Zip, Pt_Phone, Agy_Name, Agy_Street, Agy_City, Agy_State, Agy_Zip, Agy_Phone,
                                Agy_NPI, Pt_DOB, Pt_Gender, Order_description, Discharge_Plan, Clinician_Signature, 
                                Render_Phys_ID, MD_Homebound, MD_Clinical_Condition,  Date_Create, Created_by, Date_Change, 
                                Change_by)             
                        VALUES 
                            (
                                <cfqueryparam value = "#GetAssessments.Assmt_ID#" CFSQLType ="CF_SQL_INTEGER">,
                                <cfqueryparam value = "0" CFSQLType ="CF_SQL_INTEGER">,
                                <cfqueryparam value = "Form 487" CFSQLType ="CF_SQL_VARCHAR">,
                                <cfqueryparam value = "#DATEFORMAT(now(),'yyyy-mm-dd')#" CFSQLType ="CF_SQL_DATE">,
                                <cfqueryparam value = "#GetPatPayer.Sub_HIC#" CFSQLType ="CF_SQL_VARCHAR">,
                                <cfqueryparam value = "#DATEFORMAT(GetPatient.M0030_START_CARE_DT,'yyyy-mm-dd')#" CFSQLType ="CF_SQL_DATE">,
                                <cfqueryparam value = "#GetAssessments.F177#" CFSQLType ="CF_SQL_DATE">,
                                <cfqueryparam value = "#GetAssessments.F178#" CFSQLType ="CF_SQL_DATE">,
                                <cfqueryparam value = "#GetPatient.Pt_Agy_ID#" CFSQLType ="CF_SQL_VARCHAR">,
                                <cfqueryparam value = "#GetPatient.Agency_Medicare_ID#" CFSQLType ="CF_SQL_VARCHAR">,
                                <cfqueryparam value = "#GetPatient.Pt_First#" CFSQLType ="CF_SQL_VARCHAR">,
                                <cfqueryparam value = "#GetPatient.Pt_Last#" CFSQLType ="CF_SQL_VARCHAR">,
                                <cfqueryparam value = "#GetPatient.Pt_Street#" CFSQLType ="CF_SQL_VARCHAR">,
                                <cfqueryparam value = "#GetPatient.Pt_City#" CFSQLType ="CF_SQL_VARCHAR">,
                                <cfqueryparam value = "#GetPatient.Pt_State#" CFSQLType ="CF_SQL_VARCHAR">,
                                <cfqueryparam value = "#GetPatient.Pt_Zip#" CFSQLType ="CF_SQL_VARCHAR">,
                                <cfqueryparam value = "#GetPatient.Pt_Phone#" CFSQLType ="CF_SQL_VARCHAR">,
                                <cfqueryparam value = "#GetPatient.Agency_Name#" CFSQLType ="CF_SQL_VARCHAR">,
                                <cfqueryparam value = "#GetPatient.Agency_Address1#" CFSQLType ="CF_SQL_VARCHAR">,
                                <cfqueryparam value = "#GetPatient.Agency_City#" CFSQLType ="CF_SQL_VARCHAR">,
                                <cfqueryparam value = "#GetPatient.Agency_State#" CFSQLType ="CF_SQL_VARCHAR">,
                                <cfqueryparam value = "#GetPatient.Agency_Zip#" CFSQLType ="CF_SQL_VARCHAR">,
                                <cfqueryparam value = "#GetPatient.Agency_Contact_Phone#" CFSQLType ="CF_SQL_VARCHAR">,
                                <cfqueryparam value = "#GetPatient.Natl_Provider_ID#" CFSQLType ="CF_SQL_VARCHAR">,
                                <cfqueryparam value = "#DATEFORMAT(GetPatient.Pt_DOB,'yyyy-mm-dd')#" CFSQLType ="CF_SQL_DATE">,
                                <cfqueryparam value = "#GetPatient.Pt_Gender#" CFSQLType ="CF_SQL_VARCHAR">,
                                <cfqueryparam value = "#Request.Order_description#" CFSQLType ="CF_SQL_VARCHAR">,
                                <cfqueryparam value = "#GetAssessments.F260#" CFSQLType ="CF_SQL_VARCHAR">,
                                <cfqueryparam value = "" CFSQLType ="CF_SQL_VARCHAR">,
                                <cfqueryparam value = "#Val(Form.Render_Phys_ID)#" CFSQLType ="CF_SQL_INTEGER">,
                                <cfqueryparam value = "#GetPatient.MD_Homebound#" CFSQLType ="CF_SQL_VARCHAR">,
                                <cfqueryparam value = "#GetPatient.MD_Clinical_Condition#" CFSQLType ="CF_SQL_VARCHAR">,
                                <cfqueryparam value="#now()#" cfsqltype="cf_sql_timestamp">,
                                <cfqueryparam value = "#admissionEmployeeId#" CFSQLType ="CF_SQL_INTEGER">,
                                <cfqueryparam value="#now()#" cfsqltype="cf_sql_timestamp">,
                                <cfqueryparam value = "#admissionEmployeeId#" CFSQLType ="CF_SQL_INTEGER">   
                            )
                </cfquery>  
                <cfquery name="LastID" datasource="#Application.DataSrc#">
                    select LAST_INSERT_ID() as keyvalue
                </cfquery>
                <cfset url.Order_ID  = #LastID.keyvalue#/>
                <!--- <cfif form.admitaction EQ 'sendfax'>
                    <cfset url.redirect = 'chart' />
                    <cfset url.afId  = #LastID.keyvalue#/>
                    <cfinclude template="send_fax.cfm">
                    <cfabort>
                </cfif> --->
                <!--- <cfinclude template="/cron/export_PCMS4857CSV.cfm">  ---> 

        </cfif>
    </cfif>

    <!--- Keep SOC-related tables in sync with operational SOC date; skip when EMR admit differs from physician SOC --->
    <cfif operationalSOCDate NEQ '' AND NOT emrAdmitDiffersFromPhysicianSOC>
        <cfif NOT structKeyExists(request, "pat")>
            <cfset request.pat = CreateObject("component","components.general.patients").init() />
        </cfif>
        <cfset syncSocResult = request.pat.sync_soc_related_dates(Admit_ID=pAdmit_ID, Patient_ID=form.ID, SOC_Date=operationalSOCDate, Changed_By=admissionEmployeeId) />
    </cfif>

    <!--- #10421: Queue automated patient EVV when admit is submitted and payer requires EVV --->
    <cfif form.admitaction NEQ 'admissiondrafts' AND form.drafts NEQ 1>
        <cftry>
            <cfset evvPatientAuto = createObject("component", "components.evv.EVVPatientAutomation").init()>
            <cfset evvQueueResult = evvPatientAuto.queuePatientAutomation(
                patientID = val(form.ID),
                agencyID = val(session.agencyid),
                triggerSource = "admit_submit",
                admitID = val(pAdmit_ID),
                createdBy = val(admissionEmployeeId)
            )>
            <cfcatch type="any">
                <cflog file="EVVPatientAutomation" text="newadmission_action queue failed for patient #form.ID#: #cfcatch.message#">
            </cfcatch>
        </cftry>
    </cfif>
</cfif>
<!---<cfif CGI.REMOTE_ADDR EQ '103.143.7.161'>
    <cfabort> 
</cfif>--->

<cfif isAdmissionDraft>
    <cfset enc_admit_id = encrypt(pAdmit_ID, application.enckey, "AES", "Hex") />
    <cflocation url="#application.secure#/patientadmin_new/index.cfm?page=patient&ID=#session.cs.enc_patientid#&admitid=#enc_admit_id#&cat=newadmission_form" addtoken="no">
</cfif>
<cflocation url="#application.secure#/patientadmin_new/index.cfm?page=patient&ID=#session.cs.enc_patientid#&cat=Patient" addtoken="no">
