<!---
    fix_schedule_assmt_from_auth.cfm
    ----------------------------------------------------------------
    Synchronizes pSchedules.Assmt_ID with pAuths.Assmt_ID for active
    schedules whose auth is linked but assessment IDs disagree.

    Usage (always preview first):
        ?sec_key=yes_run_it_now
        ?sec_key=yes_run_it_now&Agency_ID=1150
        ?sec_key=yes_run_it_now&action=run             <-- applies update to all active agencies
        ?sec_key=yes_run_it_now&Agency_ID=1150&action=run
--->

<cfparam name="url.sec_key"   default="">
<cfparam name="url.action"    default="preview">
<cfparam name="url.Agency_ID" default="0">
<cfparam name="url.sample"    default="5">

<cfif url.sec_key NEQ "yes_run_it_now">
    <h3>Access denied.</h3>
    <p>Append <code>?sec_key=yes_run_it_now</code> to the URL to view the report (preview only).</p>
    <p>Add <code>&amp;action=run</code> to actually apply the update.</p>
    <cfabort>
</cfif>

<cfsetting requesttimeout="1800">
<cfset isRun = (url.action EQ "run")>

<cfquery name="Agencylist" datasource="#Application.DataSrc#">
    SELECT agency_id, Agency_Login, Agency_Name
    FROM   #Request.prefix_db_lookup#.Agency
    WHERE  status = 'active'
    <cfif val(url.Agency_ID) NEQ 0>
        AND agency_id = <cfqueryparam value="#url.Agency_ID#" cfsqltype="CF_SQL_INTEGER">
    </cfif>
    ORDER BY agency_id
</cfquery>

<cfset totalToFix  = 0>
<cfset totalFixed  = 0>
<cfset perAgency   = []>
<cfset sampleRows  = []>
<cfset sampleLimit = max(val(url.sample), 0)>

<cfloop query="Agencylist">
    <cfset agencyDb = "agency_" & Agencylist.agency_id>

    <cftry>
        <cfquery name="chk" datasource="#Application.DataSrc#">
            SELECT SCHEMA_NAME
            FROM   INFORMATION_SCHEMA.SCHEMATA
            WHERE  SCHEMA_NAME = <cfqueryparam value="#agencyDb#" cfsqltype="CF_SQL_VARCHAR">
        </cfquery>

        <cfif chk.recordCount EQ 0>
            <cfset arrayAppend(perAgency, {
                "agency_id"   = Agencylist.agency_id,
                "agency_name" = Agencylist.Agency_Name,
                "to_fix"      = 0,
                "fixed"       = 0,
                "status"      = "Skipped (schema not found)"
            })>
            <cfcontinue>
        </cfif>

        <cfquery name="countMismatch" datasource="#Application.DataSrc#">
            SELECT COUNT(*) AS cnt
            FROM   #agencyDb#.pSchedules    pSchedules
            JOIN   #agencyDb#.pAuths        pAuths
              ON   pSchedules.Auth_ID    = pAuths.Auth_ID
             AND   pAuths.Assmt_ID      <> pSchedules.Assmt_ID
             AND   pAuths.Assmt_ID      <> 0
             AND   pAuths.status         = 0
             AND   pSchedules.status     = 0
             AND   pSchedules.Invoice_ID = 0
        </cfquery>

        <cfset toFix = val(countMismatch.cnt)>
        <cfset totalToFix = totalToFix + toFix>

        <cfif sampleLimit GT 0 AND toFix GT 0>
            <cfquery name="sampleQ" datasource="#Application.DataSrc#" maxrows="#sampleLimit#">
                SELECT pSchedules.Schedule_ID,
                       pSchedules.Patient_ID,
                       pSchedules.Visit_Date,
                       pSchedules.Auth_ID,
                       pSchedules.Assmt_ID AS schedule_assmt,
                       pAuths.Assmt_ID     AS auth_assmt
                FROM   #agencyDb#.pSchedules pSchedules
                JOIN   #agencyDb#.pAuths     pAuths
                  ON   pSchedules.Auth_ID    = pAuths.Auth_ID
                 AND   pAuths.Assmt_ID      <> pSchedules.Assmt_ID
                 AND   pAuths.Assmt_ID      <> 0
                 AND   pAuths.status         = 0
                 AND   pSchedules.status     = 0
                 AND   pSchedules.Invoice_ID = 0
                ORDER BY pSchedules.Visit_Date DESC
            </cfquery>

            <cfloop query="sampleQ">
                <cfset arrayAppend(sampleRows, {
                    "agency_id"      = Agencylist.agency_id,
                    "schedule_id"    = sampleQ.Schedule_ID,
                    "patient_id"    = sampleQ.Patient_ID,
                    "visit_date"     = sampleQ.Visit_Date,
                    "auth_id"        = sampleQ.Auth_ID,
                    "schedule_assmt" = sampleQ.schedule_assmt,
                    "auth_assmt"     = sampleQ.auth_assmt
                })>
            </cfloop>
        </cfif>

        <cfset rowsAffected = 0>
        <cfif isRun AND toFix GT 0>
            <cfquery name="doUpdate" datasource="#Application.DataSrc#" result="updResult">
                UPDATE #agencyDb#.pSchedules pSchedules
                JOIN   #agencyDb#.pAuths     pAuths
                  ON   pSchedules.Auth_ID    = pAuths.Auth_ID
                 AND   pAuths.Assmt_ID      <> pSchedules.Assmt_ID
                 AND   pAuths.Assmt_ID      <> 0
                 AND   pAuths.status         = 0
                 AND   pSchedules.status     = 0
                 AND   pSchedules.Invoice_ID = 0
                SET    pSchedules.Assmt_ID   = pAuths.Assmt_ID
            </cfquery>
            <cfset rowsAffected = val(updResult.recordCount)>
            <cfset totalFixed   = totalFixed + rowsAffected>
        </cfif>

        <cfset arrayAppend(perAgency, {
            "agency_id"   = Agencylist.agency_id,
            "agency_name" = Agencylist.Agency_Name,
            "to_fix"      = toFix,
            "fixed"       = rowsAffected,
            "status"      = isRun ? "Updated" : "Preview only"
        })>

        <cfcatch type="any">
            <cfset arrayAppend(perAgency, {
                "agency_id"   = Agencylist.agency_id,
                "agency_name" = Agencylist.Agency_Name,
                "to_fix"      = 0,
                "fixed"       = 0,
                "status"      = "Error: " & cfcatch.message
            })>
        </cfcatch>
    </cftry>
</cfloop>

<cfoutput>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Fix pSchedules.Assmt_ID from pAuths.Assmt_ID</title>
<style>
    body{font-family:Arial,Helvetica,sans-serif;font-size:13px;padding:16px;color:##333}
    h2{margin:0 0 8px 0}
    .summary{padding:10px;border:1px solid ##ddd;background:##f8f9fa;margin-bottom:14px;border-radius:4px}
    .mode-preview{color:##0a66c2;font-weight:bold}
    .mode-run{color:##b71c1c;font-weight:bold}
    table{border-collapse:collapse;width:100%;margin-bottom:18px;font-size:12px}
    th,td{border:1px solid ##ddd;padding:6px 8px;text-align:left;vertical-align:top}
    th{background:##f3f4f6}
    tr:nth-child(even) td{background:##fafafa}
    .num{text-align:right;font-variant-numeric:tabular-nums}
    .ok{color:##2e7d32}
    .err{color:##b71c1c}
    .muted{color:##888}
    code{background:##f3f4f6;padding:1px 5px;border-radius:3px}
</style>
</head>
<body>
    <h2>Fix pSchedules.Assmt_ID &larr; pAuths.Assmt_ID</h2>

    <div class="summary">
        <div>Mode:
            <cfif isRun>
                <span class="mode-run">RUN (updates applied)</span>
            <cfelse>
                <span class="mode-preview">PREVIEW (no changes made)</span>
            </cfif>
        </div>
        <div>Agency scope:
            <cfif val(url.Agency_ID) NEQ 0>Agency_ID = #val(url.Agency_ID)#
            <cfelse>All active agencies (#Agencylist.recordCount# total)
            </cfif>
        </div>
        <div>Schedules that <cfif isRun>were updated<cfelse>would be updated</cfif>:
             <strong><cfif isRun>#totalFixed#<cfelse>#totalToFix#</cfif></strong>
        </div>
        <cfif NOT isRun>
            <div style="margin-top:6px;">
                To apply, append <code>&amp;action=run</code> to the URL.
            </div>
        </cfif>
    </div>

    <h3>Per-agency summary</h3>
    <table>
        <thead>
            <tr>
                <th>Agency ID</th>
                <th>Agency Name</th>
                <th class="num">Rows <cfif isRun>updated<cfelse>to fix</cfif></th>
                <th>Status</th>
            </tr>
        </thead>
        <tbody>
            <cfloop array="#perAgency#" index="row">
                <tr>
                    <td>#row.agency_id#</td>
                    <td>#row.agency_name#</td>
                    <td class="num">
                        <cfif isRun>#row.fixed#<cfelse>#row.to_fix#</cfif>
                    </td>
                    <td>
                        <cfif find("Error", row.status)>
                            <span class="err">#row.status#</span>
                        <cfelseif row.status EQ "Updated">
                            <span class="ok">#row.status#</span>
                        <cfelse>
                            <span class="muted">#row.status#</span>
                        </cfif>
                    </td>
                </tr>
            </cfloop>
        </tbody>
    </table>

    <cfif arrayLen(sampleRows) GT 0>
        <h3>Sample rows (up to #sampleLimit# per agency)</h3>
        <table>
            <thead>
                <tr>
                    <th>Agency</th>
                    <th>Schedule_ID</th>
                    <th>Patient_ID</th>
                    <th>Visit Date</th>
                    <th>Auth_ID</th>
                    <th>Schedule.Assmt_ID</th>
                    <th>Auth.Assmt_ID (new value)</th>
                </tr>
            </thead>
            <tbody>
                <cfloop array="#sampleRows#" index="s">
                    <tr>
                        <td>#s.agency_id#</td>
                        <td>#s.schedule_id#</td>
                        <td>#s.patient_id#</td>
                        <td>#DateFormat(s.visit_date,"mm/dd/yyyy")#</td>
                        <td>#s.auth_id#</td>
                        <td>#s.schedule_assmt#</td>
                        <td><strong>#s.auth_assmt#</strong></td>
                    </tr>
                </cfloop>
            </tbody>
        </table>
    </cfif>
</body>
</html>
</cfoutput>
