-- =====================================================================
-- 35_visitplan.sql
-- Visit Plan
--
-- GENERATED by _gen/pack.py from ../step/. DO NOT EDIT -- edit the source
-- there and re-pack, or the sha256 in MANIFEST.md stops matching.
--
-- 8 table(s), 32 ledger step(s).
--
-- ⚠ IMPORT ORDER: 01_system.sql, then all seven 1x masters, then this file. Order among
--    transactions does not matter. Re-importing costs nothing.
--
-- ⚠ STOP ON THE FIRST ERROR. Do not use `mysql --force`, and do not tick any
--    "continue on error" box. Each step records itself in `_migration_ledger`
--    immediately after its statement runs, WITHOUT checking that the statement
--    succeeded -- that is inherited from step/, where run.sh guarantees a stop by
--    running mysql without --force. Continue past an error here and a step that
--    failed is marked applied: 99_finalize.sql will then seed `migrations`, and
--    `php artisan migrate` will skip the work still owed. Both default clients
--    stop on error; the danger is turning that off.
--
-- ⚠ phpMyAdmin: UNTICK "Allow the interruption of an import".
--    If it fires, the import resumes on a NEW CONNECTION: SQL_MODE reverts to the server
--    default and every @variable dies, mid-file. Two things then break. NO_ZERO_DATE is
--    back, so any ALTER that rebuilds a table holding '0000-00-00' fails with ERROR 1292.
--    And @step / @todo / @sql are NULL, so the guard around the next payload stops meaning
--    anything. The SET SQL_MODE before every unit below limits the damage when someone
--    forgets the checkbox; it does not replace unticking it.
--
--    (STRICT_TRANS_TABLES is forced for a third case -- a value too big for its new column
--    is CLAMPED silently rather than refused. Measured on the tree as it stands, no column
--    narrows: all 674 MODIFY COLUMNs widen or are no-ops. It stays forced because the next
--    regeneration is under no obligation to keep that true.)
--
-- ⚠ Take a full backup first. The `20_cleanup` steps change data and nothing here
--    reverses them. `../audit_bukanmain_before_migrate.sql` only reads.
-- =====================================================================

-- Menus this file serves (17 links):
--   /visit-plans
--   /visit-plans/approval-pm
--   /visit-plans/calendar
--   /visit-plans/calendar/all
--   /visit-plans/calendar/head
--   /visit-plans/calendar/mm
--   /visit-plans/calendar/pm
--   /visit-plans/calendar/sm
--   /visit-plans/create
--   /visit-plans/create-for-others
--   /visit-plans/create-report
--   /visit-plans/view-all
--   /visit-plans/view-head
--   /visit-plans/view-mm
--   /visit-plans/view-sm
--   /visit-report-actions
--   /visit-report-link-with

-- --------------------------------------------------------------- prologue
-- run.sh sources step/_lib/session.sql for you. phpMyAdmin will not, so it is inlined.
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- Assert all four, not just the first. STRICT_TRANS_TABLES missing means out-of-range
-- values are clamped silently; NO_ZERO_DATE still present means any ALTER that rebuilds a
-- legacy table re-validates its '0000-00-00' rows and dies with ERROR 1292. The second is
-- the one that actually stops the migration, and it was not being checked.
SELECT IF(@@SQL_MODE LIKE '%STRICT_TRANS_TABLES%'
      AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
      AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
      AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
          'sql_mode OK - proceeding',
          (SELECT 'ABORT: sql_mode is wrong. Wanted STRICT_TRANS_TABLES + NO_AUTO_VALUE_ON_ZERO,'
           UNION ALL
           SELECT 'and NO_ZERO_DATE / NO_ZERO_IN_DATE OFF. The SET above should have done it.')
       ) AS preflight_sql_mode;

SET SESSION lock_wait_timeout = 60;
SET SESSION innodb_lock_wait_timeout = 60;

-- The ledger, copied verbatim from step/_lib/ledger.sql -- not restated, so the two
-- paths cannot disagree about its definition.
-- ---------------------------------------------------------------------
-- _lib/ledger.sql  --  the only thing here that is not in the source file
-- One row per applied step. This is the record that decides what a re-run skips,
-- what --status reports, and -- through the app-side gate -- which modules the
-- application will serve. It lives in the database on purpose: a file on one
-- operator's laptop drifts the moment someone runs a step from another machine.
--
-- Deliberately NOT in the project's PascalCase convention. It is an ops table, never
-- touched by Eloquent, and it should be visibly not-an-app-table.
--
-- `checksum` is the SHA-256 of the step's SQL payload -- the verbatim statements,
-- not the file -- so it cannot change when a comment above them is reworded.
-- _lib/steps.tsv carries the whole-file hashes for tamper detection.
--
-- ⚠ `step` IS ascii, AND THAT IS LOAD-BEARING. Every guard compares it against a
-- user variable, and a user variable carries the CONNECTION collation. Give this
-- column utf8mb4_unicode_ci and the very first step dies with ERROR 1267,
-- "Illegal mix of collations (utf8mb4_unicode_ci,IMPLICIT) and
-- (utf8mb4_0900_ai_ci,IMPLICIT) for operation '='" -- measured, that is exactly
-- how the first end-to-end run failed. ascii is a repertoire subset of latin1 and
-- of utf8mb4, so the server coerces it to whatever the connection is using,
-- whatever that turns out to be on the day. Step names are [a-z0-9_/] by
-- construction, so nothing is lost.
-- ---------------------------------------------------------------------

CREATE TABLE IF NOT EXISTS `_migration_ledger` (
  `step`        varchar(191) CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL,
  `applied_at`  datetime     NOT NULL,
  `checksum`    char(64)     NOT NULL,
  `duration_ms` int          NOT NULL,
  PRIMARY KEY (`step`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


-- --------------------------------------------------------------- preflight
-- 00_system/01_system.sql MUST already be applied. Every doc says so; until now nothing
-- enforced it, and the violation was silent for most of the tree: only three files break
-- without it (30_quotation and 40_budgetandtarget hit ERROR 1146 on a table 01_system
-- creates, and 99_finalize needs `migrations`). The other twenty import cleanly, record
-- their ledger rows, and leave a database that is half-migrated with nothing to say so.
--
-- 13 steps: the ALTER DATABASE plus the 12 CREATE TABLEs.
SET @sys_done = (SELECT COUNT(*) FROM `_migration_ledger` WHERE `step` LIKE '\_system/%');
SET @pf_sys = IF(@sys_done >= 13,
    'SELECT ''preflight: 00_system is applied'' AS preflight_system',
    'SELECT `ABORT: import 00_system/01_system.sql first. It runs the ALTER DATABASE and creates the 12 new tables that everything here assumes exist.`');
PREPARE _pf FROM @pf_sys; EXECUTE _pf; DEALLOCATE PREPARE _pf;

-- --------------------------------------------------------------- preflight
-- WAS THIS DATABASE MIGRATED FROM A DIFFERENT VERSION OF THIS FILE?
--
-- `_migration_ledger.checksum` is the SHA-256 of each step's payload. It is written 632
-- times across the tree and, until this block existed, read never -- so a corrected payload
-- re-issued under the same step name was skipped forever on any database that had recorded
-- the old one, silently and permanently.
SELECT COUNT(*) INTO @ck_bad FROM `_migration_ledger`
 WHERE `step` IN ('visitplan/10_alter', 'visitplan/20_cleanup', 'visitplan/30_assert', 'visitplan/40_fk', 'visitplanassignment/10_alter', 'visitplanassignment/20_cleanup', 'visitplanassignment/30_assert', 'visitplanassignment/40_fk', 'visitplancompanycpdetail/10_alter', 'visitplancompanycpdetail/20_cleanup', 'visitplancompanycpdetail/30_assert', 'visitplancompanycpdetail/40_fk', 'visitplandetail/10_alter', 'visitplandetail/20_cleanup', 'visitplandetail/30_assert', 'visitplandetail/40_fk', 'visitplandetailassignment/10_alter', 'visitplandetailassignment/20_cleanup', 'visitplandetailassignment/30_assert', 'visitplandetailassignment/40_fk', 'visitplanfrienddetail/10_alter', 'visitplanfrienddetail/20_cleanup', 'visitplanfrienddetail/30_assert', 'visitplanfrienddetail/40_fk', 'visitplanlink/10_alter', 'visitplanlink/20_cleanup', 'visitplanlink/30_assert', 'visitplanlink/40_fk', 'visitplanprincipalvisitdetail/10_alter', 'visitplanprincipalvisitdetail/20_cleanup', 'visitplanprincipalvisitdetail/30_assert', 'visitplanprincipalvisitdetail/40_fk')
   AND CONCAT(`step`, ':', `checksum`) NOT IN ('visitplan/10_alter:811d4e38c039e456c936152d27cf038b0a2c5fe6b0ff5eb4787c94eadaef7890', 'visitplan/20_cleanup:280dae28f934e72d478980d6e5cd43feee7c67bb8179834dfcb14524937bb433', 'visitplan/30_assert:52c107cb3a34ad3f6a54b5d751d432d4ae8f9c4a1e70dbc9b020334e5af89253', 'visitplan/40_fk:3e1f03e66290ba48526e30d69900f3046bfaaa8002aa55bfefcf3e16d9eefb9d', 'visitplanassignment/10_alter:e9dbf785a2f77f2b4e28edd303d8e6244445748aad6204e17240f95b08851c5b', 'visitplanassignment/20_cleanup:6ec3cf83375219b7ac9f19faca8930f6731a5af2bffe4db8b81f1cb21f0f0643', 'visitplanassignment/30_assert:0c143b899a18f610a69b7b711b40e96e486501350187930172977b9b92aca4d1', 'visitplanassignment/40_fk:b584b4434daff4f5e6ddc7a3d1f1e4652ce46d2295cc22efe6f46939bddb4c9c', 'visitplancompanycpdetail/10_alter:bc8e809b37346217cd40c2035a87fc18c0222a873374e83741f84bcd9216b92a', 'visitplancompanycpdetail/20_cleanup:79f7b8f41a216023d4ce57139b0d2a8c3632c7d10e5b168e43f67ce3cb96aa11', 'visitplancompanycpdetail/30_assert:8cb4f746a2151bce15653296efc8915d370c14d222b43e5803d83333007e7c94', 'visitplancompanycpdetail/40_fk:dc78b7a8f6e43bf2a90cd98a38817fb88b20822bb9d868da6fb3dcd6b63381cc', 'visitplandetail/10_alter:803d6420ac1de8ad4a91c33d94ec18c16d6c7bbb084491efc17fc116a1b2d50f', 'visitplandetail/20_cleanup:f9f5ff77fdfcf3329f2196825c1a97f707eafd2f58b25c3f5beeafce2d87fc10', 'visitplandetail/30_assert:a17fc7662c3bb8dd5f387201ebe8772ce501656e6c1ea7f1d85f7039d68be784', 'visitplandetail/40_fk:cc9a035a3342509474fec4620a9749e89dff14cb53ea5a8b9fb82d92020b941e', 'visitplandetailassignment/10_alter:beef5062a662daf2a6d85b86082bb4d00fd87037ee39a2f1331e0a0b7ebe15a6', 'visitplandetailassignment/20_cleanup:a7376843ab8ab0337842912032f263fd2c5abad59a424dfb9b7751a617fc0d41', 'visitplandetailassignment/30_assert:79026528a0ed1093abf79a0b0dd2442fa3dd6a5df8e0e131e7ecefc1bfabb5bd', 'visitplandetailassignment/40_fk:7b1b1093e51632a3dd21f509ebd32baaf623907cea95e220137f1ef99698ca25', 'visitplanfrienddetail/10_alter:5dcd20f6cd5d8bdac74e7c4c80943d81a83e5c2ad1a77050a0624c291bbea23d', 'visitplanfrienddetail/20_cleanup:a3b6f3de56019bc91fc1ca9e66250b5d7bfd65029a13715e094e004d766a2db5', 'visitplanfrienddetail/30_assert:273899f0bf015a925cef123a8f2e3bd7f3fc0832943190ba94f53b1a9a473c31', 'visitplanfrienddetail/40_fk:e6de5d7fa810112e9b294317f53d41b437637805a05f665b1e01f37da294d4a9', 'visitplanlink/10_alter:c651add505498653feec3ab3d22eb2f7307cfb2112e4866209a4447576b51a61', 'visitplanlink/20_cleanup:6320ed3e6f9f9bee95da8f332fe2292ad7c39366ad276dd18592284697fb4ad1', 'visitplanlink/30_assert:4bdde90663710bfa800099fcf6859b1083f0583b3711b1d0447a314ef59adaf8', 'visitplanlink/40_fk:a247d7c019be6cecbc1075c106494e1ddd1dfa2a21e5fa0c896bf594e3d1950e', 'visitplanprincipalvisitdetail/10_alter:354517847220437c7aa9e4d6408b9eae2a78b03c391164133ae5d93c37648d7e', 'visitplanprincipalvisitdetail/20_cleanup:549da404ff3f8126cdd00e5cd1ce53c84d37596e8e32dca07a3c26ade5d67121', 'visitplanprincipalvisitdetail/30_assert:6f0eefb6e3400a0be1f7e9b32a02af39c10c275fbf20cd600df899aea2ef6463', 'visitplanprincipalvisitdetail/40_fk:4ade6a06707e76e56352493f17d310bb39a42dae8623d20f9ca059ebae27ad2d');
SET @pf_ck = IF(@ck_bad = 0,
    'SELECT ''preflight: ledger matches this file'' AS preflight_checksum',
    CONCAT('SELECT `ABORT: ', @ck_bad, ' step(s) here were applied from a DIFFERENT version of this file. Their payloads changed. Compare before re-importing; do not delete ledger rows blindly.`'));
PREPARE _pf FROM @pf_ck; EXECUTE _pf; DEALLOCATE PREPARE _pf;

-- ---------------------------------------------------------------------
-- unit: visitplan    (transaction)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- visitplan/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'visitplan/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `visitplan`
  DROP INDEX `VisitPlanStatusID`', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
SET @sql = IF(@todo, 'ALTER TABLE `visitplan`
  MODIFY COLUMN `VisitPlanStatusID` int DEFAULT NULL,
  MODIFY COLUMN `DivisionID` int DEFAULT NULL,
  MODIFY COLUMN `UserIDInput` int DEFAULT NULL,
  MODIFY COLUMN `UserIDSales` int DEFAULT NULL,
  MODIFY COLUMN `CompanyID` int DEFAULT NULL,
  MODIFY COLUMN `ProjectID` int DEFAULT NULL,
  MODIFY COLUMN `CompanyCPID` int DEFAULT NULL,
  MODIFY COLUMN `UserIDVisitWith` int DEFAULT NULL,
  MODIFY COLUMN `VisitingPrincipalID` int DEFAULT NULL,
  MODIFY COLUMN `VisitPrincipalCPID` int DEFAULT NULL,
  ADD INDEX `DivisionID` (`DivisionID`),
  ADD INDEX `UserIDInput` (`UserIDInput`,`UserIDSales`,`CompanyID`,`CompanyCPID`,`UserIDVisitWith`),
  ADD INDEX `visitplan_CompanyCPID` (`CompanyCPID`),
  ADD INDEX `visitplan_CompanyID` (`CompanyID`),
  ADD INDEX `visitplan_ProjectID` (`ProjectID`),
  ADD INDEX `visitplan_UserIDSales` (`UserIDSales`),
  ADD INDEX `visitplan_UserIDVisitWith` (`UserIDVisitWith`),
  ADD INDEX `visitplan_VisitingPrincipalID` (`VisitingPrincipalID`),
  ADD INDEX `visitplan_VisitPrincipalCPID` (`VisitPrincipalCPID`),
  ADD INDEX `VisitPlanStatusID_3` (`VisitPlanStatusID`,`DivisionID`,`UserIDInput`,`UserIDSales`,`CompanyID`,`CompanyCPID`,`UserIDVisitWith`),
  ADD INDEX `VisitPlanStatusID` (`VisitPlanStatusID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '811d4e38c039e456c936152d27cf038b0a2c5fe6b0ff5eb4787c94eadaef7890', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- visitplan/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'visitplan/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `visitplan` c
  LEFT JOIN `companycp` p0 ON c.`CompanyCPID` = p0.`ID`
  LEFT JOIN `company` p1 ON c.`CompanyID` = p1.`ID`
  LEFT JOIN `division` p2 ON c.`DivisionID` = p2.`ID`
  LEFT JOIN `companyproject` p3 ON c.`ProjectID` = p3.`ID`
  LEFT JOIN `users` p4 ON c.`UserIDInput` = p4.`ID`
  LEFT JOIN `users` p5 ON c.`UserIDSales` = p5.`ID`
  LEFT JOIN `users` p6 ON c.`UserIDVisitWith` = p6.`ID`
  LEFT JOIN `visitplanstatus` p7 ON c.`VisitPlanStatusID` = p7.`ID`
  LEFT JOIN `principalcp` p8 ON c.`VisitPrincipalCPID` = p8.`ID`
  LEFT JOIN `principal` p9 ON c.`VisitingPrincipalID` = p9.`ID`
   SET
       c.`CompanyCPID` = IF((c.`CompanyCPID` IS NOT NULL AND (c.`CompanyCPID` = 0 OR p0.`ID` IS NULL)), NULL, c.`CompanyCPID`),
       c.`CompanyID` = IF((c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p1.`ID` IS NULL)), NULL, c.`CompanyID`),
       c.`DivisionID` = IF((c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p2.`ID` IS NULL)), NULL, c.`DivisionID`),
       c.`ProjectID` = IF((c.`ProjectID` IS NOT NULL AND (c.`ProjectID` = 0 OR p3.`ID` IS NULL)), NULL, c.`ProjectID`),
       c.`UserIDInput` = IF((c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p4.`ID` IS NULL)), NULL, c.`UserIDInput`),
       c.`UserIDSales` = IF((c.`UserIDSales` IS NOT NULL AND (c.`UserIDSales` = 0 OR p5.`ID` IS NULL)), NULL, c.`UserIDSales`),
       c.`UserIDVisitWith` = IF((c.`UserIDVisitWith` IS NOT NULL AND (c.`UserIDVisitWith` = 0 OR p6.`ID` IS NULL)), NULL, c.`UserIDVisitWith`),
       c.`VisitPlanStatusID` = IF((c.`VisitPlanStatusID` IS NOT NULL AND (c.`VisitPlanStatusID` = 0 OR p7.`ID` IS NULL)), NULL, c.`VisitPlanStatusID`),
       c.`VisitPrincipalCPID` = IF((c.`VisitPrincipalCPID` IS NOT NULL AND (c.`VisitPrincipalCPID` = 0 OR p8.`ID` IS NULL)), NULL, c.`VisitPrincipalCPID`),
       c.`VisitingPrincipalID` = IF((c.`VisitingPrincipalID` IS NOT NULL AND (c.`VisitingPrincipalID` = 0 OR p9.`ID` IS NULL)), NULL, c.`VisitingPrincipalID`)
 WHERE  (c.`CompanyCPID` IS NOT NULL AND (c.`CompanyCPID` = 0 OR p0.`ID` IS NULL))
    OR (c.`CompanyID` IS NOT NULL AND (c.`CompanyID` = 0 OR p1.`ID` IS NULL))
    OR (c.`DivisionID` IS NOT NULL AND (c.`DivisionID` = 0 OR p2.`ID` IS NULL))
    OR (c.`ProjectID` IS NOT NULL AND (c.`ProjectID` = 0 OR p3.`ID` IS NULL))
    OR (c.`UserIDInput` IS NOT NULL AND (c.`UserIDInput` = 0 OR p4.`ID` IS NULL))
    OR (c.`UserIDSales` IS NOT NULL AND (c.`UserIDSales` = 0 OR p5.`ID` IS NULL))
    OR (c.`UserIDVisitWith` IS NOT NULL AND (c.`UserIDVisitWith` = 0 OR p6.`ID` IS NULL))
    OR (c.`VisitPlanStatusID` IS NOT NULL AND (c.`VisitPlanStatusID` = 0 OR p7.`ID` IS NULL))
    OR (c.`VisitPrincipalCPID` IS NOT NULL AND (c.`VisitPrincipalCPID` = 0 OR p8.`ID` IS NULL))
    OR (c.`VisitingPrincipalID` IS NOT NULL AND (c.`VisitingPrincipalID` = 0 OR p9.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '280dae28f934e72d478980d6e5cd43feee7c67bb8179834dfcb14524937bb433', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- visitplan/30_assert  --  source section 7b
-- Orphan assertion over this table's 10 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'visitplan/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `visitplan` c
  LEFT JOIN `companycp` p0 ON c.`CompanyCPID` = p0.`ID`
  LEFT JOIN `company` p1 ON c.`CompanyID` = p1.`ID`
  LEFT JOIN `division` p2 ON c.`DivisionID` = p2.`ID`
  LEFT JOIN `companyproject` p3 ON c.`ProjectID` = p3.`ID`
  LEFT JOIN `users` p4 ON c.`UserIDInput` = p4.`ID`
  LEFT JOIN `users` p5 ON c.`UserIDSales` = p5.`ID`
  LEFT JOIN `users` p6 ON c.`UserIDVisitWith` = p6.`ID`
  LEFT JOIN `visitplanstatus` p7 ON c.`VisitPlanStatusID` = p7.`ID`
  LEFT JOIN `principalcp` p8 ON c.`VisitPrincipalCPID` = p8.`ID`
  LEFT JOIN `principal` p9 ON c.`VisitingPrincipalID` = p9.`ID`
 WHERE  (c.`CompanyCPID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`CompanyID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`DivisionID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`ProjectID` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`UserIDInput` IS NOT NULL AND p4.`ID` IS NULL)
    OR (c.`UserIDSales` IS NOT NULL AND p5.`ID` IS NULL)
    OR (c.`UserIDVisitWith` IS NOT NULL AND p6.`ID` IS NULL)
    OR (c.`VisitPlanStatusID` IS NOT NULL AND p7.`ID` IS NULL)
    OR (c.`VisitPrincipalCPID` IS NOT NULL AND p8.`ID` IS NULL)
    OR (c.`VisitingPrincipalID` IS NOT NULL AND p9.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'visitplan: orphan check OK - 0 rows across 10 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `visitplan` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '52c107cb3a34ad3f6a54b5d751d432d4ae8f9c4a1e70dbc9b020334e5af89253', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- visitplan/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'visitplan/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `visitplan`
  ADD CONSTRAINT `visitplan_CompanyCPID` FOREIGN KEY (`CompanyCPID`) REFERENCES `companycp` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `visitplan_CompanyID` FOREIGN KEY (`CompanyID`) REFERENCES `company` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `visitplan_DivisionID` FOREIGN KEY (`DivisionID`) REFERENCES `division` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `visitplan_ProjectID` FOREIGN KEY (`ProjectID`) REFERENCES `companyproject` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `visitplan_UserIDInput` FOREIGN KEY (`UserIDInput`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `visitplan_UserIDSales` FOREIGN KEY (`UserIDSales`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `visitplan_UserIDVisitWith` FOREIGN KEY (`UserIDVisitWith`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `visitplan_VisitPlanStatusID` FOREIGN KEY (`VisitPlanStatusID`) REFERENCES `visitplanstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `visitplan_VisitPrincipalCPID` FOREIGN KEY (`VisitPrincipalCPID`) REFERENCES `principalcp` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `visitplan_VisitingPrincipalID` FOREIGN KEY (`VisitingPrincipalID`) REFERENCES `principal` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '3e1f03e66290ba48526e30d69900f3046bfaaa8002aa55bfefcf3e16d9eefb9d', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: visitplanassignment    (detail, owned by visitplan)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- visitplanassignment/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'visitplanassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `visitplanassignment`
  MODIFY COLUMN `VisitPlanID` int DEFAULT NULL,
  MODIFY COLUMN `UserID` int DEFAULT NULL,
  MODIFY COLUMN `VisitPlanStatusID` int DEFAULT NULL,
  ADD INDEX `visitplanassignment_UserID` (`UserID`),
  ADD INDEX `visitplanassignment_VisitPlanStatusID` (`VisitPlanStatusID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'e9dbf785a2f77f2b4e28edd303d8e6244445748aad6204e17240f95b08851c5b', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- visitplanassignment/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'visitplanassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `visitplanassignment` c
  LEFT JOIN `users` p0 ON c.`UserID` = p0.`ID`
  LEFT JOIN `visitplan` p1 ON c.`VisitPlanID` = p1.`ID`
  LEFT JOIN `visitplanstatus` p2 ON c.`VisitPlanStatusID` = p2.`ID`
   SET
       c.`UserID` = IF((c.`UserID` IS NOT NULL AND (c.`UserID` = 0 OR p0.`ID` IS NULL)), NULL, c.`UserID`),
       c.`VisitPlanID` = IF((c.`VisitPlanID` IS NOT NULL AND (c.`VisitPlanID` = 0 OR p1.`ID` IS NULL)), NULL, c.`VisitPlanID`),
       c.`VisitPlanStatusID` = IF((c.`VisitPlanStatusID` IS NOT NULL AND (c.`VisitPlanStatusID` = 0 OR p2.`ID` IS NULL)), NULL, c.`VisitPlanStatusID`)
 WHERE  (c.`UserID` IS NOT NULL AND (c.`UserID` = 0 OR p0.`ID` IS NULL))
    OR (c.`VisitPlanID` IS NOT NULL AND (c.`VisitPlanID` = 0 OR p1.`ID` IS NULL))
    OR (c.`VisitPlanStatusID` IS NOT NULL AND (c.`VisitPlanStatusID` = 0 OR p2.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '6ec3cf83375219b7ac9f19faca8930f6731a5af2bffe4db8b81f1cb21f0f0643', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- visitplanassignment/30_assert  --  source section 7b
-- Orphan assertion over this table's 3 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'visitplanassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `visitplanassignment` c
  LEFT JOIN `users` p0 ON c.`UserID` = p0.`ID`
  LEFT JOIN `visitplan` p1 ON c.`VisitPlanID` = p1.`ID`
  LEFT JOIN `visitplanstatus` p2 ON c.`VisitPlanStatusID` = p2.`ID`
 WHERE  (c.`UserID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`VisitPlanID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`VisitPlanStatusID` IS NOT NULL AND p2.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'visitplanassignment: orphan check OK - 0 rows across 3 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `visitplanassignment` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '0c143b899a18f610a69b7b711b40e96e486501350187930172977b9b92aca4d1', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- visitplanassignment/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'visitplanassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `visitplanassignment`
  ADD CONSTRAINT `visitplanassignment_UserID` FOREIGN KEY (`UserID`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `visitplanassignment_VisitPlanID` FOREIGN KEY (`VisitPlanID`) REFERENCES `visitplan` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `visitplanassignment_VisitPlanStatusID` FOREIGN KEY (`VisitPlanStatusID`) REFERENCES `visitplanstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'b584b4434daff4f5e6ddc7a3d1f1e4652ce46d2295cc22efe6f46939bddb4c9c', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: visitplancompanycpdetail    (detail, owned by visitplan)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- visitplancompanycpdetail/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'visitplancompanycpdetail/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `visitplancompanycpdetail`
  MODIFY COLUMN `VisitPlanID` int DEFAULT NULL,
  MODIFY COLUMN `CompanyCPID` int DEFAULT NULL,
  ADD INDEX `visitplancompanycpdetail_CompanyCPID` (`CompanyCPID`),
  ADD INDEX `visitplancompanycpdetail_VisitPlanID` (`VisitPlanID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'bc8e809b37346217cd40c2035a87fc18c0222a873374e83741f84bcd9216b92a', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- visitplancompanycpdetail/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'visitplancompanycpdetail/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `visitplancompanycpdetail` c
  LEFT JOIN `companycp` p0 ON c.`CompanyCPID` = p0.`ID`
  LEFT JOIN `visitplan` p1 ON c.`VisitPlanID` = p1.`ID`
   SET
       c.`CompanyCPID` = IF((c.`CompanyCPID` IS NOT NULL AND (c.`CompanyCPID` = 0 OR p0.`ID` IS NULL)), NULL, c.`CompanyCPID`),
       c.`VisitPlanID` = IF((c.`VisitPlanID` IS NOT NULL AND (c.`VisitPlanID` = 0 OR p1.`ID` IS NULL)), NULL, c.`VisitPlanID`)
 WHERE  (c.`CompanyCPID` IS NOT NULL AND (c.`CompanyCPID` = 0 OR p0.`ID` IS NULL))
    OR (c.`VisitPlanID` IS NOT NULL AND (c.`VisitPlanID` = 0 OR p1.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '79f7b8f41a216023d4ce57139b0d2a8c3632c7d10e5b168e43f67ce3cb96aa11', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- visitplancompanycpdetail/30_assert  --  source section 7b
-- Orphan assertion over this table's 2 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'visitplancompanycpdetail/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `visitplancompanycpdetail` c
  LEFT JOIN `companycp` p0 ON c.`CompanyCPID` = p0.`ID`
  LEFT JOIN `visitplan` p1 ON c.`VisitPlanID` = p1.`ID`
 WHERE  (c.`CompanyCPID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`VisitPlanID` IS NOT NULL AND p1.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'visitplancompanycpdetail: orphan check OK - 0 rows across 2 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `visitplancompanycpdetail` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '8cb4f746a2151bce15653296efc8915d370c14d222b43e5803d83333007e7c94', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- visitplancompanycpdetail/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'visitplancompanycpdetail/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `visitplancompanycpdetail`
  ADD CONSTRAINT `visitplancompanycpdetail_CompanyCPID` FOREIGN KEY (`CompanyCPID`) REFERENCES `companycp` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `visitplancompanycpdetail_VisitPlanID` FOREIGN KEY (`VisitPlanID`) REFERENCES `visitplan` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'dc78b7a8f6e43bf2a90cd98a38817fb88b20822bb9d868da6fb3dcd6b63381cc', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: visitplandetail    (detail, owned by visitplan)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- visitplandetail/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'visitplandetail/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `visitplandetail`
  MODIFY COLUMN `VisitPlanID` int DEFAULT NULL,
  MODIFY COLUMN `ActionID` int DEFAULT NULL,
  MODIFY COLUMN `ProjectID` int DEFAULT NULL,
  MODIFY COLUMN `PrincipalID` int DEFAULT NULL,
  MODIFY COLUMN `BarangID` int DEFAULT NULL,
  MODIFY COLUMN `VisitActionStatusID` int DEFAULT NULL,
  ADD INDEX `visitplandetail_ActionID` (`ActionID`),
  ADD INDEX `visitplandetail_BarangID` (`BarangID`),
  ADD INDEX `visitplandetail_PrincipalID` (`PrincipalID`),
  ADD INDEX `visitplandetail_ProjectID` (`ProjectID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '803d6420ac1de8ad4a91c33d94ec18c16d6c7bbb084491efc17fc116a1b2d50f', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- visitplandetail/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'visitplandetail/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `visitplandetail` c
  LEFT JOIN `action` p0 ON c.`ActionID` = p0.`ID`
  LEFT JOIN `barang` p1 ON c.`BarangID` = p1.`ID`
  LEFT JOIN `principal` p2 ON c.`PrincipalID` = p2.`ID`
  LEFT JOIN `companyprojectdetailcc` p3 ON c.`ProjectID` = p3.`ID`
  LEFT JOIN `visitplanstatus` p4 ON c.`VisitActionStatusID` = p4.`ID`
  LEFT JOIN `visitplan` p5 ON c.`VisitPlanID` = p5.`ID`
   SET
       c.`ActionID` = IF((c.`ActionID` IS NOT NULL AND (c.`ActionID` = 0 OR p0.`ID` IS NULL)), NULL, c.`ActionID`),
       c.`BarangID` = IF((c.`BarangID` IS NOT NULL AND (c.`BarangID` = 0 OR p1.`ID` IS NULL)), NULL, c.`BarangID`),
       c.`PrincipalID` = IF((c.`PrincipalID` IS NOT NULL AND (c.`PrincipalID` = 0 OR p2.`ID` IS NULL)), NULL, c.`PrincipalID`),
       c.`ProjectID` = IF((c.`ProjectID` IS NOT NULL AND (c.`ProjectID` = 0 OR p3.`ID` IS NULL)), NULL, c.`ProjectID`),
       c.`VisitActionStatusID` = IF((c.`VisitActionStatusID` IS NOT NULL AND (c.`VisitActionStatusID` = 0 OR p4.`ID` IS NULL)), NULL, c.`VisitActionStatusID`),
       c.`VisitPlanID` = IF((c.`VisitPlanID` IS NOT NULL AND (c.`VisitPlanID` = 0 OR p5.`ID` IS NULL)), NULL, c.`VisitPlanID`)
 WHERE  (c.`ActionID` IS NOT NULL AND (c.`ActionID` = 0 OR p0.`ID` IS NULL))
    OR (c.`BarangID` IS NOT NULL AND (c.`BarangID` = 0 OR p1.`ID` IS NULL))
    OR (c.`PrincipalID` IS NOT NULL AND (c.`PrincipalID` = 0 OR p2.`ID` IS NULL))
    OR (c.`ProjectID` IS NOT NULL AND (c.`ProjectID` = 0 OR p3.`ID` IS NULL))
    OR (c.`VisitActionStatusID` IS NOT NULL AND (c.`VisitActionStatusID` = 0 OR p4.`ID` IS NULL))
    OR (c.`VisitPlanID` IS NOT NULL AND (c.`VisitPlanID` = 0 OR p5.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'f9f5ff77fdfcf3329f2196825c1a97f707eafd2f58b25c3f5beeafce2d87fc10', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- visitplandetail/30_assert  --  source section 7b
-- Orphan assertion over this table's 6 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'visitplandetail/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `visitplandetail` c
  LEFT JOIN `action` p0 ON c.`ActionID` = p0.`ID`
  LEFT JOIN `barang` p1 ON c.`BarangID` = p1.`ID`
  LEFT JOIN `principal` p2 ON c.`PrincipalID` = p2.`ID`
  LEFT JOIN `companyprojectdetailcc` p3 ON c.`ProjectID` = p3.`ID`
  LEFT JOIN `visitplanstatus` p4 ON c.`VisitActionStatusID` = p4.`ID`
  LEFT JOIN `visitplan` p5 ON c.`VisitPlanID` = p5.`ID`
 WHERE  (c.`ActionID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`BarangID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`PrincipalID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`ProjectID` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`VisitActionStatusID` IS NOT NULL AND p4.`ID` IS NULL)
    OR (c.`VisitPlanID` IS NOT NULL AND p5.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'visitplandetail: orphan check OK - 0 rows across 6 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `visitplandetail` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'a17fc7662c3bb8dd5f387201ebe8772ce501656e6c1ea7f1d85f7039d68be784', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- visitplandetail/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'visitplandetail/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `visitplandetail`
  ADD CONSTRAINT `visitplandetail_ActionID` FOREIGN KEY (`ActionID`) REFERENCES `action` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `visitplandetail_BarangID` FOREIGN KEY (`BarangID`) REFERENCES `barang` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `visitplandetail_PrincipalID` FOREIGN KEY (`PrincipalID`) REFERENCES `principal` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `visitplandetail_ProjectID` FOREIGN KEY (`ProjectID`) REFERENCES `companyprojectdetailcc` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `visitplandetail_VisitActionStatusID` FOREIGN KEY (`VisitActionStatusID`) REFERENCES `visitplanstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `visitplandetail_VisitPlanID` FOREIGN KEY (`VisitPlanID`) REFERENCES `visitplan` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'cc9a035a3342509474fec4620a9749e89dff14cb53ea5a8b9fb82d92020b941e', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: visitplandetailassignment    (detail, owned by visitplan)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- visitplandetailassignment/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'visitplandetailassignment/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `visitplandetailassignment`
  MODIFY COLUMN `VisitPlanID` int DEFAULT NULL,
  MODIFY COLUMN `VisitPlanDetailID` int DEFAULT NULL,
  MODIFY COLUMN `UserID` int DEFAULT NULL,
  MODIFY COLUMN `VisitPlanStatusID` int DEFAULT NULL,
  MODIFY COLUMN `VisitActionStatusID` int DEFAULT NULL,
  ADD INDEX `visitplandetailassignment_UserID` (`UserID`),
  ADD INDEX `visitplandetailassignment_VisitPlanDetailID` (`VisitPlanDetailID`),
  ADD INDEX `visitplandetailassignment_VisitPlanStatusID` (`VisitPlanStatusID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'beef5062a662daf2a6d85b86082bb4d00fd87037ee39a2f1331e0a0b7ebe15a6', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- visitplandetailassignment/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'visitplandetailassignment/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `visitplandetailassignment` c
  LEFT JOIN `users` p0 ON c.`UserID` = p0.`ID`
  LEFT JOIN `visitplanstatus` p1 ON c.`VisitActionStatusID` = p1.`ID`
  LEFT JOIN `visitplandetail` p2 ON c.`VisitPlanDetailID` = p2.`ID`
  LEFT JOIN `visitplan` p3 ON c.`VisitPlanID` = p3.`ID`
  LEFT JOIN `visitplanstatus` p4 ON c.`VisitPlanStatusID` = p4.`ID`
   SET
       c.`UserID` = IF((c.`UserID` IS NOT NULL AND (c.`UserID` = 0 OR p0.`ID` IS NULL)), NULL, c.`UserID`),
       c.`VisitActionStatusID` = IF((c.`VisitActionStatusID` IS NOT NULL AND (c.`VisitActionStatusID` = 0 OR p1.`ID` IS NULL)), NULL, c.`VisitActionStatusID`),
       c.`VisitPlanDetailID` = IF((c.`VisitPlanDetailID` IS NOT NULL AND (c.`VisitPlanDetailID` = 0 OR p2.`ID` IS NULL)), NULL, c.`VisitPlanDetailID`),
       c.`VisitPlanID` = IF((c.`VisitPlanID` IS NOT NULL AND (c.`VisitPlanID` = 0 OR p3.`ID` IS NULL)), NULL, c.`VisitPlanID`),
       c.`VisitPlanStatusID` = IF((c.`VisitPlanStatusID` IS NOT NULL AND (c.`VisitPlanStatusID` = 0 OR p4.`ID` IS NULL)), NULL, c.`VisitPlanStatusID`)
 WHERE  (c.`UserID` IS NOT NULL AND (c.`UserID` = 0 OR p0.`ID` IS NULL))
    OR (c.`VisitActionStatusID` IS NOT NULL AND (c.`VisitActionStatusID` = 0 OR p1.`ID` IS NULL))
    OR (c.`VisitPlanDetailID` IS NOT NULL AND (c.`VisitPlanDetailID` = 0 OR p2.`ID` IS NULL))
    OR (c.`VisitPlanID` IS NOT NULL AND (c.`VisitPlanID` = 0 OR p3.`ID` IS NULL))
    OR (c.`VisitPlanStatusID` IS NOT NULL AND (c.`VisitPlanStatusID` = 0 OR p4.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'a7376843ab8ab0337842912032f263fd2c5abad59a424dfb9b7751a617fc0d41', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- visitplandetailassignment/30_assert  --  source section 7b
-- Orphan assertion over this table's 5 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'visitplandetailassignment/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `visitplandetailassignment` c
  LEFT JOIN `users` p0 ON c.`UserID` = p0.`ID`
  LEFT JOIN `visitplanstatus` p1 ON c.`VisitActionStatusID` = p1.`ID`
  LEFT JOIN `visitplandetail` p2 ON c.`VisitPlanDetailID` = p2.`ID`
  LEFT JOIN `visitplan` p3 ON c.`VisitPlanID` = p3.`ID`
  LEFT JOIN `visitplanstatus` p4 ON c.`VisitPlanStatusID` = p4.`ID`
 WHERE  (c.`UserID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`VisitActionStatusID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`VisitPlanDetailID` IS NOT NULL AND p2.`ID` IS NULL)
    OR (c.`VisitPlanID` IS NOT NULL AND p3.`ID` IS NULL)
    OR (c.`VisitPlanStatusID` IS NOT NULL AND p4.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'visitplandetailassignment: orphan check OK - 0 rows across 5 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `visitplandetailassignment` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '79026528a0ed1093abf79a0b0dd2442fa3dd6a5df8e0e131e7ecefc1bfabb5bd', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- visitplandetailassignment/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'visitplandetailassignment/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `visitplandetailassignment`
  ADD CONSTRAINT `visitplandetailassignment_UserID` FOREIGN KEY (`UserID`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `visitplandetailassignment_VisitActionStatusID` FOREIGN KEY (`VisitActionStatusID`) REFERENCES `visitplanstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `visitplandetailassignment_VisitPlanDetailID` FOREIGN KEY (`VisitPlanDetailID`) REFERENCES `visitplandetail` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `visitplandetailassignment_VisitPlanID` FOREIGN KEY (`VisitPlanID`) REFERENCES `visitplan` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `visitplandetailassignment_VisitPlanStatusID` FOREIGN KEY (`VisitPlanStatusID`) REFERENCES `visitplanstatus` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '7b1b1093e51632a3dd21f509ebd32baaf623907cea95e220137f1ef99698ca25', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: visitplanfrienddetail    (detail, owned by visitplan)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- visitplanfrienddetail/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'visitplanfrienddetail/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `visitplanfrienddetail`
  MODIFY COLUMN `VisitPlanID` int DEFAULT NULL,
  MODIFY COLUMN `UserIDVisitWith` int DEFAULT NULL,
  ADD INDEX `visitplanfrienddetail_UserIDVisitWith` (`UserIDVisitWith`),
  ADD INDEX `visitplanfrienddetail_VisitPlanID` (`VisitPlanID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '5dcd20f6cd5d8bdac74e7c4c80943d81a83e5c2ad1a77050a0624c291bbea23d', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- visitplanfrienddetail/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'visitplanfrienddetail/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `visitplanfrienddetail` c
  LEFT JOIN `users` p0 ON c.`UserIDVisitWith` = p0.`ID`
  LEFT JOIN `visitplan` p1 ON c.`VisitPlanID` = p1.`ID`
   SET
       c.`UserIDVisitWith` = IF((c.`UserIDVisitWith` IS NOT NULL AND (c.`UserIDVisitWith` = 0 OR p0.`ID` IS NULL)), NULL, c.`UserIDVisitWith`),
       c.`VisitPlanID` = IF((c.`VisitPlanID` IS NOT NULL AND (c.`VisitPlanID` = 0 OR p1.`ID` IS NULL)), NULL, c.`VisitPlanID`)
 WHERE  (c.`UserIDVisitWith` IS NOT NULL AND (c.`UserIDVisitWith` = 0 OR p0.`ID` IS NULL))
    OR (c.`VisitPlanID` IS NOT NULL AND (c.`VisitPlanID` = 0 OR p1.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'a3b6f3de56019bc91fc1ca9e66250b5d7bfd65029a13715e094e004d766a2db5', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- visitplanfrienddetail/30_assert  --  source section 7b
-- Orphan assertion over this table's 2 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'visitplanfrienddetail/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `visitplanfrienddetail` c
  LEFT JOIN `users` p0 ON c.`UserIDVisitWith` = p0.`ID`
  LEFT JOIN `visitplan` p1 ON c.`VisitPlanID` = p1.`ID`
 WHERE  (c.`UserIDVisitWith` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`VisitPlanID` IS NOT NULL AND p1.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'visitplanfrienddetail: orphan check OK - 0 rows across 2 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `visitplanfrienddetail` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '273899f0bf015a925cef123a8f2e3bd7f3fc0832943190ba94f53b1a9a473c31', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- visitplanfrienddetail/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'visitplanfrienddetail/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `visitplanfrienddetail`
  ADD CONSTRAINT `visitplanfrienddetail_UserIDVisitWith` FOREIGN KEY (`UserIDVisitWith`) REFERENCES `users` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `visitplanfrienddetail_VisitPlanID` FOREIGN KEY (`VisitPlanID`) REFERENCES `visitplan` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'e6de5d7fa810112e9b294317f53d41b437637805a05f665b1e01f37da294d4a9', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: visitplanlink    (detail, owned by visitplan)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- visitplanlink/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'visitplanlink/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `visitplanlink` MODIFY COLUMN `VisitPlanID` int DEFAULT NULL', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'c651add505498653feec3ab3d22eb2f7307cfb2112e4866209a4447576b51a61', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- visitplanlink/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'visitplanlink/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `visitplanlink` c
  LEFT JOIN `visitplan` p0 ON c.`VisitPlanID` = p0.`ID`
   SET
       c.`VisitPlanID` = IF((c.`VisitPlanID` IS NOT NULL AND (c.`VisitPlanID` = 0 OR p0.`ID` IS NULL)), NULL, c.`VisitPlanID`)
 WHERE  (c.`VisitPlanID` IS NOT NULL AND (c.`VisitPlanID` = 0 OR p0.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '6320ed3e6f9f9bee95da8f332fe2292ad7c39366ad276dd18592284697fb4ad1', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- visitplanlink/30_assert  --  source section 7b
-- Orphan assertion over this table's 1 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'visitplanlink/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `visitplanlink` c
  LEFT JOIN `visitplan` p0 ON c.`VisitPlanID` = p0.`ID`
 WHERE  (c.`VisitPlanID` IS NOT NULL AND p0.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'visitplanlink: orphan check OK - 0 rows across 1 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `visitplanlink` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '4bdde90663710bfa800099fcf6859b1083f0583b3711b1d0447a314ef59adaf8', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- visitplanlink/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'visitplanlink/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `visitplanlink` ADD CONSTRAINT `visitplanlink_VisitPlanID` FOREIGN KEY (`VisitPlanID`) REFERENCES `visitplan` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), 'a247d7c019be6cecbc1075c106494e1ddd1dfa2a21e5fa0c896bf594e3d1950e', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- ---------------------------------------------------------------------
-- unit: visitplanprincipalvisitdetail    (detail, owned by visitplan)
-- ---------------------------------------------------------------------
             AND @@SQL_MODE LIKE '%NO_AUTO_VALUE_ON_ZERO%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_DATE%'
             AND @@SQL_MODE NOT LIKE '%NO_ZERO_IN_DATE%',
        @@SQL_MODE,
        CONCAT(REPLACE(REPLACE(@@SQL_MODE, 'NO_ZERO_IN_DATE', ''), 'NO_ZERO_DATE', ''),
               ',NO_AUTO_VALUE_ON_ZERO,STRICT_TRANS_TABLES'));
-- ---------------------------------------------------------------------
-- visitplanprincipalvisitdetail/10_alter  --  source section A
-- The merged ALTER: new columns, type/charset changes, column order, NULL relaxation
-- and the indexes every foreign key needs -- ONE statement, so InnoDB rebuilds this
-- table ONCE. The original migration split these across five sections and rebuilt some
-- tables four times; that is where its 12 hours went. Do not split this back up.
--
-- Clause order is the original section order (3b, 3d, 3e, 4, 7), which is what keeps
-- every ADD COLUMN ... AFTER positioned exactly as before.
-- ---------------------------------------------------------------------

SET @step = 'visitplanprincipalvisitdetail/10_alter';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `visitplanprincipalvisitdetail`
  MODIFY COLUMN `VisitPlanID` int DEFAULT NULL,
  MODIFY COLUMN `VisitingPrincipalID` int DEFAULT NULL,
  MODIFY COLUMN `VisitingPrincipalCPID` int DEFAULT NULL,
  ADD INDEX `visitplanprincipalvisitdetail_VisitingPrincipalCPID` (`VisitingPrincipalCPID`),
  ADD INDEX `visitplanprincipalvisitdetail_VisitingPrincipalID` (`VisitingPrincipalID`),
  ADD INDEX `visitplanprincipalvisitdetail_VisitPlanID` (`VisitPlanID`)', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '354517847220437c7aa9e4d6408b9eae2a78b03c391164133ae5d93c37648d7e', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- visitplanprincipalvisitdetail/20_cleanup  --  source section B (= the original sections 5 and 6, merged)
-- 0-sentinels AND orphaned references -> NULL, one pass per table.
--     section 5:  WHERE `c` = 0
--     section 6:  WHERE `c` IS NOT NULL AND parent.ID IS NULL
--     merged   :  WHERE `c` IS NOT NULL AND (`c` = 0 OR parent.ID IS NULL)
-- Every LEFT JOIN is a primary-key equality, so none of them can multiply rows.
--
-- DATA CHANGE, and this script cannot reverse it. Run the audit first.
-- In its own transaction, with the ledger row inside it: either the cleanup and the
-- record of it both land, or neither does.
-- ---------------------------------------------------------------------

START TRANSACTION;

SET @step = 'visitplanprincipalvisitdetail/20_cleanup';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'UPDATE `visitplanprincipalvisitdetail` c
  LEFT JOIN `visitplan` p0 ON c.`VisitPlanID` = p0.`ID`
  LEFT JOIN `principalcp` p1 ON c.`VisitingPrincipalCPID` = p1.`ID`
  LEFT JOIN `principal` p2 ON c.`VisitingPrincipalID` = p2.`ID`
   SET
       c.`VisitPlanID` = IF((c.`VisitPlanID` IS NOT NULL AND (c.`VisitPlanID` = 0 OR p0.`ID` IS NULL)), NULL, c.`VisitPlanID`),
       c.`VisitingPrincipalCPID` = IF((c.`VisitingPrincipalCPID` IS NOT NULL AND (c.`VisitingPrincipalCPID` = 0 OR p1.`ID` IS NULL)), NULL, c.`VisitingPrincipalCPID`),
       c.`VisitingPrincipalID` = IF((c.`VisitingPrincipalID` IS NOT NULL AND (c.`VisitingPrincipalID` = 0 OR p2.`ID` IS NULL)), NULL, c.`VisitingPrincipalID`)
 WHERE  (c.`VisitPlanID` IS NOT NULL AND (c.`VisitPlanID` = 0 OR p0.`ID` IS NULL))
    OR (c.`VisitingPrincipalCPID` IS NOT NULL AND (c.`VisitingPrincipalCPID` = 0 OR p1.`ID` IS NULL))
    OR (c.`VisitingPrincipalID` IS NOT NULL AND (c.`VisitingPrincipalID` = 0 OR p2.`ID` IS NULL))', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '549da404ff3f8126cdd00e5cd1ce53c84d37596e8e32dca07a3c26ade5d67121', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;

COMMIT;
-- ---------------------------------------------------------------------
-- visitplanprincipalvisitdetail/30_assert  --  source section 7b
-- Orphan assertion over this table's 3 foreign-key relationships.
--
-- This is what pays for 40_fk being fast. The original created the constraints with
-- FOREIGN_KEY_CHECKS ON so a row the cleanup missed would abort the run, and paid for it
-- with a full table copy per constraint. This buys the same protection with one indexed
-- pass, and 40_fk then adds the constraints as metadata only.
--
-- NOT ledger-guarded on the way in, unlike every other phase: it only reads, and the
-- point of it is to be re-runnable. It does record its ledger row -- 40_fk requires it.
--
-- IF THIS ABORTS: a row survived 20_cleanup. Same stop-and-look event the original would
-- have hit as ERROR 1452 inside section 8, but nothing has been created yet.
-- ---------------------------------------------------------------------

SET @step = 'visitplanprincipalvisitdetail/30_assert';
SET @t0 = NOW(3);
SET @orphans = 0;
SELECT COUNT(*) INTO @n FROM `visitplanprincipalvisitdetail` c
  LEFT JOIN `visitplan` p0 ON c.`VisitPlanID` = p0.`ID`
  LEFT JOIN `principalcp` p1 ON c.`VisitingPrincipalCPID` = p1.`ID`
  LEFT JOIN `principal` p2 ON c.`VisitingPrincipalID` = p2.`ID`
 WHERE  (c.`VisitPlanID` IS NOT NULL AND p0.`ID` IS NULL)
    OR (c.`VisitingPrincipalCPID` IS NOT NULL AND p1.`ID` IS NULL)
    OR (c.`VisitingPrincipalID` IS NOT NULL AND p2.`ID` IS NULL);
SET @orphans = @orphans + @n;

-- Two-row subquery on the false branch: ERROR 1242, an abort, before 40_fk runs.
SELECT IF(@orphans = 0,
          'visitplanprincipalvisitdetail: orphan check OK - 0 rows across 3 relationships',
          (SELECT CONCAT('ABORT: ', @orphans, ' rows in `visitplanprincipalvisitdetail` still reference a parent that does not exist')
           UNION ALL
           SELECT 'Run 20_cleanup for this table first. Do NOT skip this check.')
       ) AS preflight_orphans;

INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '6f0eefb6e3400a0be1f7e9b32a02af39c10c275fbf20cd600df899aea2ef6463', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;
-- ---------------------------------------------------------------------
-- visitplanprincipalvisitdetail/40_fk  --  source section 8
-- The constraints, one ALTER for the whole table.
--
-- FOREIGN_KEY_CHECKS is turned OFF for this statement and restored afterwards. With
-- checks on InnoDB cannot add a foreign key in place -- it copies the whole table and
-- re-validates every row, which is where the original migration's 154 table copies
-- came from. The validation is not skipped, it MOVED: 30_assert proves zero orphans
-- and refuses to let this run otherwise.
-- ---------------------------------------------------------------------

SET @fk_prev = @@FOREIGN_KEY_CHECKS;

SET @step = 'visitplanprincipalvisitdetail/40_fk';
SET @todo = (SELECT COUNT(*) = 0 FROM `_migration_ledger` WHERE `step` = @step);
SET @t0 = NOW(3);
SET @sql = IF(@todo, 'ALTER TABLE `visitplanprincipalvisitdetail`
  ADD CONSTRAINT `visitplanprincipalvisitdetail_VisitPlanID` FOREIGN KEY (`VisitPlanID`) REFERENCES `visitplan` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `visitplanprincipalvisitdetail_VisitingPrincipalCPID` FOREIGN KEY (`VisitingPrincipalCPID`) REFERENCES `principalcp` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  ADD CONSTRAINT `visitplanprincipalvisitdetail_VisitingPrincipalID` FOREIGN KEY (`VisitingPrincipalID`) REFERENCES `principal` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT', 'DO 0');
PREPARE _step FROM @sql; EXECUTE _step; DEALLOCATE PREPARE _step;
INSERT INTO `_migration_ledger` (`step`, `applied_at`, `checksum`, `duration_ms`)
     VALUES (@step, NOW(), '4ade6a06707e76e56352493f17d310bb39a42dae8623d20f9ca059ebae27ad2d', TIMESTAMPDIFF(MICROSECOND, @t0, NOW(3)) DIV 1000)
ON DUPLICATE KEY UPDATE `step` = `step`;


-- --------------------------------------------------------------- postflight
-- DID THE WORK ACTUALLY LAND?
--
-- Every step records itself in `_migration_ledger` immediately after its statement runs,
-- WITHOUT checking that the statement succeeded. That is inherited from step/ unchanged,
-- and there it is safe because run.sh runs mysql without --force, so the first error stops
-- everything. Imported by hand, the client decides -- and "continue on error" would leave
-- failed steps marked applied.
--
-- So this file checks its own work against information_schema before it finishes. It is
-- the only thing here that is NOT copied from step/. It reads; it changes nothing.

-- postflight-set: fk
SET @want_fk = 32;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_fk, @miss_fk
  FROM (SELECT 'visitplan.visitplan_CompanyCPID' AS n UNION ALL SELECT 'visitplan.visitplan_CompanyID' UNION ALL SELECT 'visitplan.visitplan_DivisionID' UNION ALL SELECT 'visitplan.visitplan_ProjectID' UNION ALL SELECT 'visitplan.visitplan_UserIDInput' UNION ALL SELECT 'visitplan.visitplan_UserIDSales' UNION ALL SELECT 'visitplan.visitplan_UserIDVisitWith' UNION ALL SELECT 'visitplan.visitplan_VisitPlanStatusID' UNION ALL SELECT 'visitplan.visitplan_VisitPrincipalCPID' UNION ALL SELECT 'visitplan.visitplan_VisitingPrincipalID' UNION ALL SELECT 'visitplanassignment.visitplanassignment_UserID' UNION ALL SELECT 'visitplanassignment.visitplanassignment_VisitPlanID' UNION ALL SELECT 'visitplanassignment.visitplanassignment_VisitPlanStatusID' UNION ALL SELECT 'visitplancompanycpdetail.visitplancompanycpdetail_CompanyCPID' UNION ALL SELECT 'visitplancompanycpdetail.visitplancompanycpdetail_VisitPlanID' UNION ALL SELECT 'visitplandetail.visitplandetail_ActionID' UNION ALL SELECT 'visitplandetail.visitplandetail_BarangID' UNION ALL SELECT 'visitplandetail.visitplandetail_PrincipalID' UNION ALL SELECT 'visitplandetail.visitplandetail_ProjectID' UNION ALL SELECT 'visitplandetail.visitplandetail_VisitActionStatusID' UNION ALL SELECT 'visitplandetail.visitplandetail_VisitPlanID' UNION ALL SELECT 'visitplandetailassignment.visitplandetailassignment_UserID' UNION ALL SELECT 'visitplandetailassignment.visitplandetailassignment_VisitActionStatusID' UNION ALL SELECT 'visitplandetailassignment.visitplandetailassignment_VisitPlanDetailID' UNION ALL SELECT 'visitplandetailassignment.visitplandetailassignment_VisitPlanID' UNION ALL SELECT 'visitplandetailassignment.visitplandetailassignment_VisitPlanStatusID' UNION ALL SELECT 'visitplanfrienddetail.visitplanfrienddetail_UserIDVisitWith' UNION ALL SELECT 'visitplanfrienddetail.visitplanfrienddetail_VisitPlanID' UNION ALL SELECT 'visitplanlink.visitplanlink_VisitPlanID' UNION ALL SELECT 'visitplanprincipalvisitdetail.visitplanprincipalvisitdetail_VisitPlanID' UNION ALL SELECT 'visitplanprincipalvisitdetail.visitplanprincipalvisitdetail_VisitingPrincipalCPID' UNION ALL SELECT 'visitplanprincipalvisitdetail.visitplanprincipalvisitdetail_VisitingPrincipalID') _w
 WHERE n NOT IN (SELECT CONCAT(TABLE_NAME, '.', CONSTRAINT_NAME) FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = DATABASE() AND CONSTRAINT_TYPE = 'FOREIGN KEY');
SET @have_fk = @want_fk - @missn_fk;
SET @pf_fk = IF(@missn_fk = 0,
    CONCAT('SELECT ''postflight foreign keys: ', @have_fk, '/', @want_fk, ' present'' AS postflight_fk'),
    CONCAT('SELECT `ABORT postflight: MISSING foreign keys: ', @miss_fk,
           ' -- ', @missn_fk, ' of ', @want_fk, ' absent. A step is recorded in',
           ' _migration_ledger but did not take effect.`'));
PREPARE _pf FROM @pf_fk; EXECUTE _pf; DEALLOCATE PREPARE _pf;

-- postflight-set: idx
SET @want_idx = 27;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_idx, @miss_idx
  FROM (SELECT 'visitplan.DivisionID' AS n UNION ALL SELECT 'visitplan.UserIDInput' UNION ALL SELECT 'visitplan.VisitPlanStatusID' UNION ALL SELECT 'visitplan.VisitPlanStatusID_3' UNION ALL SELECT 'visitplan.visitplan_CompanyCPID' UNION ALL SELECT 'visitplan.visitplan_CompanyID' UNION ALL SELECT 'visitplan.visitplan_ProjectID' UNION ALL SELECT 'visitplan.visitplan_UserIDSales' UNION ALL SELECT 'visitplan.visitplan_UserIDVisitWith' UNION ALL SELECT 'visitplan.visitplan_VisitPrincipalCPID' UNION ALL SELECT 'visitplan.visitplan_VisitingPrincipalID' UNION ALL SELECT 'visitplanassignment.visitplanassignment_UserID' UNION ALL SELECT 'visitplanassignment.visitplanassignment_VisitPlanStatusID' UNION ALL SELECT 'visitplancompanycpdetail.visitplancompanycpdetail_CompanyCPID' UNION ALL SELECT 'visitplancompanycpdetail.visitplancompanycpdetail_VisitPlanID' UNION ALL SELECT 'visitplandetail.visitplandetail_ActionID' UNION ALL SELECT 'visitplandetail.visitplandetail_BarangID' UNION ALL SELECT 'visitplandetail.visitplandetail_PrincipalID' UNION ALL SELECT 'visitplandetail.visitplandetail_ProjectID' UNION ALL SELECT 'visitplandetailassignment.visitplandetailassignment_UserID' UNION ALL SELECT 'visitplandetailassignment.visitplandetailassignment_VisitPlanDetailID' UNION ALL SELECT 'visitplandetailassignment.visitplandetailassignment_VisitPlanStatusID' UNION ALL SELECT 'visitplanfrienddetail.visitplanfrienddetail_UserIDVisitWith' UNION ALL SELECT 'visitplanfrienddetail.visitplanfrienddetail_VisitPlanID' UNION ALL SELECT 'visitplanprincipalvisitdetail.visitplanprincipalvisitdetail_VisitPlanID' UNION ALL SELECT 'visitplanprincipalvisitdetail.visitplanprincipalvisitdetail_VisitingPrincipalCPID' UNION ALL SELECT 'visitplanprincipalvisitdetail.visitplanprincipalvisitdetail_VisitingPrincipalID') _w
 WHERE n NOT IN (SELECT CONCAT(TABLE_NAME, '.', INDEX_NAME) FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE());
SET @have_idx = @want_idx - @missn_idx;
SET @pf_idx = IF(@missn_idx = 0,
    CONCAT('SELECT ''postflight indexes: ', @have_idx, '/', @want_idx, ' present'' AS postflight_idx'),
    CONCAT('SELECT `ABORT postflight: MISSING indexes: ', @miss_idx,
           ' -- ', @missn_idx, ' of ', @want_idx, ' absent. A step is recorded in',
           ' _migration_ledger but did not take effect.`'));
PREPARE _pf FROM @pf_idx; EXECUTE _pf; DEALLOCATE PREPARE _pf;

-- postflight-set: typ
SET @want_typ = 32;
SELECT COUNT(*), IFNULL(SUBSTRING(GROUP_CONCAT(n ORDER BY n SEPARATOR ', '), 1, 60), '')
  INTO @missn_typ, @miss_typ
  FROM (SELECT 'visitplan.CompanyCPID.int' AS n UNION ALL SELECT 'visitplan.CompanyID.int' UNION ALL SELECT 'visitplan.DivisionID.int' UNION ALL SELECT 'visitplan.ProjectID.int' UNION ALL SELECT 'visitplan.UserIDInput.int' UNION ALL SELECT 'visitplan.UserIDSales.int' UNION ALL SELECT 'visitplan.UserIDVisitWith.int' UNION ALL SELECT 'visitplan.VisitPlanStatusID.int' UNION ALL SELECT 'visitplan.VisitPrincipalCPID.int' UNION ALL SELECT 'visitplan.VisitingPrincipalID.int' UNION ALL SELECT 'visitplanassignment.UserID.int' UNION ALL SELECT 'visitplanassignment.VisitPlanID.int' UNION ALL SELECT 'visitplanassignment.VisitPlanStatusID.int' UNION ALL SELECT 'visitplancompanycpdetail.CompanyCPID.int' UNION ALL SELECT 'visitplancompanycpdetail.VisitPlanID.int' UNION ALL SELECT 'visitplandetail.ActionID.int' UNION ALL SELECT 'visitplandetail.BarangID.int' UNION ALL SELECT 'visitplandetail.PrincipalID.int' UNION ALL SELECT 'visitplandetail.ProjectID.int' UNION ALL SELECT 'visitplandetail.VisitActionStatusID.int' UNION ALL SELECT 'visitplandetail.VisitPlanID.int' UNION ALL SELECT 'visitplandetailassignment.UserID.int' UNION ALL SELECT 'visitplandetailassignment.VisitActionStatusID.int' UNION ALL SELECT 'visitplandetailassignment.VisitPlanDetailID.int' UNION ALL SELECT 'visitplandetailassignment.VisitPlanID.int' UNION ALL SELECT 'visitplandetailassignment.VisitPlanStatusID.int' UNION ALL SELECT 'visitplanfrienddetail.UserIDVisitWith.int' UNION ALL SELECT 'visitplanfrienddetail.VisitPlanID.int' UNION ALL SELECT 'visitplanlink.VisitPlanID.int' UNION ALL SELECT 'visitplanprincipalvisitdetail.VisitPlanID.int' UNION ALL SELECT 'visitplanprincipalvisitdetail.VisitingPrincipalCPID.int' UNION ALL SELECT 'visitplanprincipalvisitdetail.VisitingPrincipalID.int') _w
 WHERE n NOT IN (SELECT CONCAT(TABLE_NAME, '.', COLUMN_NAME, '.', DATA_TYPE) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE());
SET @have_typ = @want_typ - @missn_typ;
SET @pf_typ = IF(@missn_typ = 0,
    CONCAT('SELECT ''postflight retyped columns: ', @have_typ, '/', @want_typ, ' present'' AS postflight_typ'),
    CONCAT('SELECT `ABORT postflight: MISSING retyped columns: ', @miss_typ,
           ' -- ', @missn_typ, ' of ', @want_typ, ' absent. A step is recorded in',
           ' _migration_ledger but did not take effect.`'));
PREPARE _pf FROM @pf_typ; EXECUTE _pf; DEALLOCATE PREPARE _pf;

-- --------------------------------------------------------------- restore
-- IFNULL on all four: if phpMyAdmin resumed this import on a fresh connection the
-- @OLD_ variables are gone, and a bare SET from NULL is ERROR 1231.
--
-- The CAST is on the two timeouts and NOWHERE ELSE, on purpose. An INTEGER system
-- variable rejects IFNULL()'s result type outright (ERROR 1232, every time, not only
-- when NULL). FOREIGN_KEY_CHECKS is a boolean and SQL_MODE is a set; both accept a
-- string result, so they need no CAST. Do not "fix" the asymmetry, and do not copy
-- line 3's shape onto a new integer variable.
SET SESSION lock_wait_timeout = CAST(IFNULL(@OLD_LOCK_WAIT, 86400) AS UNSIGNED);
SET SESSION innodb_lock_wait_timeout = CAST(IFNULL(@OLD_INNODB_LOCK_WAIT, 50) AS UNSIGNED);
