<?php
/**
 * Seed Service Templates Catalog · items + callout resolutions.
 *
 * Ports sitetracker16's production template library into rsflow.dspera. Idempotent:
 * re-runs replace items per template (DELETE + INSERT) so evolving a template is safe.
 * Callout resolutions upsert on `code`.
 */
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', dirname(__DIR__));
require_once ROOT . DS . 'config' . DS . 'config.php';
require_once ROOT . DS . 'core' . DS . 'Application.php';
require_once ROOT . DS . 'core' . DS . 'Model.php';
require_once ROOT . DS . 'core' . DS . 'DB.php';

$db = new DB();

/* ── Template item schemas (portable — mirror sitetracker16) ──────── */

$TEMPLATES = [

    // ──────────────────────────────────────────────────────────── 74 items
    'SITE-MONTHLY' => [
        ['PERIMETER',           'site_signage_clean',           'Site signage clean and visible',                     'CHECK',   true],
        ['PERIMETER',           'fence_intact',                 'Fence intact / gate locking',                        'CHECK',   true],
        ['PERIMETER',           'site_clean',                   'Site clean (no debris, vegetation cut)',             'CHECK',   true],
        ['PERIMETER',           'warning_lights_working',       'All warning lights working',                         'CHECK',   true],

        ['ACCESS_SECURITY',     'site_access_perimeter',        'Site Access & Perimeter',                            'CHECK',   true],
        ['ACCESS_SECURITY',     'locking_mechanisms',           'Locking Mechanisms',                                 'CHECK',   true],
        ['ACCESS_SECURITY',     'shelter_cabinet_exterior',     'Shelter / Cabinet Exterior',                         'CHECK',   true],
        ['ACCESS_SECURITY',     'locks_door_seals_ok',          'Locks + door seals OK',                              'CHECK',   true],

        ['SAFETY',              'fire_extinguishers_ok',        'Fire extinguishers present + within expiry',         'CHECK',   true],
        ['SAFETY',              'lighting_working',             'Lighting working',                                   'CHECK',   true],

        ['EQUIPMENT_WALKAROUND','gen_running_ok',               'All generators running OK (visual + audible)',       'CHECK',   true],
        ['EQUIPMENT_WALKAROUND','ac_cooling_ok',                'All AC units cooling OK',                            'CHECK',   true],
        ['EQUIPMENT_WALKAROUND','battery_banks_ok',             'All battery banks visually OK (no swelling, no leaks)','CHECK',true],
        ['EQUIPMENT_WALKAROUND','rectifier_ok',                 'Rectifier / DC plant OK (no alarms)',                'CHECK',   true],

        ['JANITORIAL',          'shelter_clean',                'Shelter floor / walls clean',                        'CHECK',   true],
        ['JANITORIAL',          'general_cleanliness',          'General cleanliness',                                'CHECK',   true],

        ['POWER_READINGS',      'grid_meter_reading',           'Grid energy meter reading',                          'NUMBER',  true, 'kWh'],
        ['POWER_READINGS',      'voltage_ry',                   'Voltage R-Y (phase-to-phase)',                       'NUMBER',  true, 'V'],
        ['POWER_READINGS',      'voltage_rb',                   'Voltage R-B',                                        'NUMBER',  true, 'V'],
        ['POWER_READINGS',      'voltage_yb',                   'Voltage Y-B',                                        'NUMBER',  true, 'V'],
        ['POWER_READINGS',      'voltage_rn',                   'Voltage R-N (phase-to-neutral)',                     'NUMBER',  true, 'V'],
        ['POWER_READINGS',      'voltage_yn',                   'Voltage Y-N',                                        'NUMBER',  true, 'V'],
        ['POWER_READINGS',      'voltage_bn',                   'Voltage B-N',                                        'NUMBER',  true, 'V'],
        ['POWER_READINGS',      'voltage_ne',                   'Voltage N-E (neutral-to-earth)',                     'NUMBER',  true, 'V'],
        ['POWER_READINGS',      'current_r',                    'Current R',                                          'NUMBER',  true, 'A'],
        ['POWER_READINGS',      'current_y',                    'Current Y',                                          'NUMBER',  true, 'A'],
        ['POWER_READINGS',      'current_b',                    'Current B',                                          'NUMBER',  true, 'A'],
        ['POWER_READINGS',      'current_n',                    'Current N',                                          'NUMBER',  true, 'A'],
        ['POWER_READINGS',      'total_load',                   'Total load',                                         'NUMBER',  true, 'kW'],

        ['PHOTOS',              'site_overview_photo',          'Site overview photo',                                'PHOTO',   true],
        ['PHOTOS',              'login_arrival_photo',          'Login arrival photo',                                'PHOTO',   true],
        ['PHOTOS',              'logout_departure_photo',       'Logout departure photo',                             'PHOTO',   true],

        ['EARTHING',            'earthing_system_value',        'Earthing system value',                              'NUMBER',  false, 'Ω'],

        ['SURGE_ARRESTORS',     'surge_arrestor_dg_status',     'Surge arrestor Type-1 DG status',                    'CHECK',   false],
        ['SURGE_ARRESTORS',     'surge_arrestor_rectifier_status','Surge arrestor Type-1 rectifier status',           'CHECK',   false],
        ['SURGE_ARRESTORS',     'surge_arrestor_photo',         'Surge arrestor photo',                               'PHOTO',   false],

        ['SOLAR_INFO',          'solar_panels_present',         'Solar panels present at this site?',                 'CHECK',   false],
        ['SOLAR_INFO',          'hybrid_system_status',         'Hybrid system status',                               'CHECK',   false, null, null, 'solar_panels_present', 'YES'],

        ['SOLAR',               'cleaning_tools_photo',         'Cleaning tools present photo',                       'PHOTO',   false, null, null, 'solar_panels_present', 'YES'],
        ['SOLAR',               'panel_photos_before',          'Panel photos before cleaning',                       'PHOTO',   false, null, null, 'solar_panels_present', 'YES'],
        ['SOLAR',               'solar_combiner_damage',        'Any damaged solar combiner box door?',               'CHECK',   false, null, null, 'solar_panels_present', 'YES'],
        ['SOLAR',               'solar_foundation_sinking',     'Any signs of sinking panel foundation?',             'CHECK',   false, null, null, 'solar_panels_present', 'YES'],
        ['SOLAR',               'panel_photos_after',           'Panel photos after cleaning',                        'PHOTO',   false, null, null, 'solar_panels_present', 'YES'],

        ['SPILLAGE',            'any_spillage_onsite',          'Any spillage on site?',                              'CHECK',   false],
        ['SPILLAGE',            'spillage_source_photo',        'Source of spillage photo',                           'PHOTO',   false, null, null, 'any_spillage_onsite', 'YES'],
        ['SPILLAGE',            'spillage_area_photo',          'Affected area photo',                                'PHOTO',   false, null, null, 'any_spillage_onsite', 'YES'],

        ['GROUNDING',           'grounding_cable_present',      'Presence of grounding cable',                        'CHECK',   false],
        ['GROUNDING',           'grounding_bar_present',        'Presence of grounding bar',                          'CHECK',   false],

        ['TOWER_LIGHTS',        'tower_maintenance_status',     'Tower maintenance status',                           'CHECK',   false],
        ['TOWER_LIGHTS',        'aviation_light_present',       'Aviation light present?',                            'CHECK',   false],
        ['TOWER_LIGHTS',        'aviation_light_working',       'Aviation light working?',                            'CHECK',   false, null, null, 'aviation_light_present', 'YES'],

        ['AC_INCOMER',          'ac_incomer_condition_ok',      'AC incomer condition OK?',                           'CHECK',   false],
        ['AC_INCOMER',          'ac_incomer_photo_if_nok',      'AC incomer photo (if NOK)',                          'PHOTO',   false, null, null, 'ac_incomer_condition_ok', 'NO'],

        ['SHELTER',             'shelter_floor_photo',          'Shelter floor photo',                                'PHOTO',   false],
        ['SHELTER',             'shelter_ceiling_photo',        'Shelter ceiling photo',                              'PHOTO',   false],
        ['SHELTER',             'shelter_outside_front_photo',  'Shelter outside photo (front)',                      'PHOTO',   false],
        ['SHELTER',             'shelter_outside_back_photo',   'Shelter outside photo (back)',                       'PHOTO',   false],
        ['SHELTER',             'shelter_lighting_working',     'Shelter lighting working count',                     'NUMBER',  false, 'fixtures'],
        ['SHELTER',             'shelter_lighting_not_working', 'Shelter lighting not-working count',                 'NUMBER',  false, 'fixtures'],

        ['RMS',                 'rms_condition',                'RMS condition',                                      'CHECK',   false],
        ['RMS',                 'rms_status_online',            'RMS status online?',                                 'CHECK',   false],

        ['ALARM_TEST',          'ac_power_failure_alarm_test',  'AC power failure alarm test',                        'CHECK',   false],
        ['ALARM_TEST',          'common_dg_alarm',              'Common DG alarm',                                    'CHECK',   false],
        ['ALARM_TEST',          'dg_running_alarm',             'DG running alarm',                                   'CHECK',   false],
        ['ALARM_TEST',          'discharge_alarm',              'Discharge alarm',                                    'CHECK',   false],
        ['ALARM_TEST',          'high_temp_alarm',              'High temperature alarm',                             'CHECK',   false],
        ['ALARM_TEST',          'low_fuel_alarm',               'Low fuel alarm',                                     'CHECK',   false],
        ['ALARM_TEST',          'mpf_alarm',                    'MPF alarm',                                          'CHECK',   false],
        ['ALARM_TEST',          'rectifier_failure_alarm',      'Rectifier failure alarm',                            'CHECK',   false],
        ['ALARM_TEST',          'alarm_screenprint_photo',      'Alarm screen print photo',                           'PHOTO',   false],

        ['CLOSEOUT',            'padlock_exit_photo',           'Padlock exit photo',                                 'PHOTO',   false],
        ['CLOSEOUT',            'any_remaining_activity',       'Any remaining activity?',                            'CHECK',   false],
    ],

    // ──────────────────────────────────────────────────────────── 14 items
    'GEN-SVC-250' => [
        ['SERVICE',   'engine_oil_change',        'Engine oil change',                          'CHECK',  true],
        ['SERVICE',   'oil_filter_change',        'Engine oil filter change',                   'CHECK',  true],
        ['SERVICE',   'fuel_filter_change',       'Fuel filter change',                         'CHECK',  true],
        ['SERVICE',   'air_filter_cleaned',       'Air filter cleaned / replaced',              'CHECK',  true],
        ['SERVICE',   'coolant_level_check',      'Coolant level check',                        'CHECK',  true],
        ['SERVICE',   'belt_tension_check',       'Belt tension check',                         'CHECK',  true],
        ['SERVICE',   'battery_terminals_clean',  'Battery terminals clean + tight',            'CHECK',  true],
        ['SERVICE',   'visual_leak_check',        'Visual leak check (oil / fuel / coolant)',   'CHECK',  true],
        ['TEST_RUN',  'test_run_voltage',         'Test run — voltage',                         'NUMBER', true,  'V'],
        ['TEST_RUN',  'test_run_frequency',       'Test run — frequency',                       'NUMBER', true,  'Hz'],
        ['TEST_RUN',  'final_run_hours_after',    'Final run-hours after service',              'NUMBER', true,  'hrs'],
        ['PHOTOS',    'engine_before_service',    'Engine before service',                      'PHOTO',  true],
        ['PHOTOS',    'engine_after_service',     'Engine after service',                       'PHOTO',  true],
        ['PHOTOS',    'service_log_sticker',      'Service log sticker',                        'PHOTO',  true],
    ],

    // ──────────────────────────────────────────────────────────── 18 items
    'GEN-SVC-500' => [
        ['SERVICE',   'engine_oil_change',        'Engine oil change',                          'CHECK',  true],
        ['SERVICE',   'oil_filter_change',        'Engine oil filter change',                   'CHECK',  true],
        ['SERVICE',   'fuel_filter_change',       'Fuel filter change',                         'CHECK',  true],
        ['SERVICE',   'air_filter_cleaned',       'Air filter cleaned / replaced',              'CHECK',  true],
        ['SERVICE',   'coolant_level_check',      'Coolant level check',                        'CHECK',  true],
        ['SERVICE',   'belt_tension_check',       'Belt tension check',                         'CHECK',  true],
        ['SERVICE',   'battery_terminals_clean',  'Battery terminals clean + tight',            'CHECK',  true],
        ['SERVICE',   'visual_leak_check',        'Visual leak check (oil / fuel / coolant)',   'CHECK',  true],
        ['EXTENDED',  'valve_clearance_check',    'Valve clearance check / adjust',             'CHECK',  true],
        ['EXTENDED',  'injector_inspection',      'Injector inspection',                        'CHECK',  true],
        ['EXTENDED',  'coolant_change',           'Coolant change',                             'CHECK',  true],
        ['EXTENDED',  'radiator_clean',           'Radiator clean',                             'CHECK',  true],
        ['EXTENDED',  'glow_plugs_check',         'Glow plugs / spark plugs (if applicable)',   'CHECK',  false],
        ['TEST_RUN',  'test_run_voltage',         'Test run — voltage',                         'NUMBER', true,  'V'],
        ['TEST_RUN',  'test_run_frequency',       'Test run — frequency',                       'NUMBER', true,  'Hz'],
        ['TEST_RUN',  'final_run_hours_after',    'Final run-hours after service',              'NUMBER', true,  'hrs'],
        ['PHOTOS',    'engine_before_service',    'Engine before service',                      'PHOTO',  true],
        ['PHOTOS',    'engine_after_service',     'Engine after service',                       'PHOTO',  true],
        ['PHOTOS',    'service_log_sticker',      'Service log sticker',                        'PHOTO',  true],
    ],

    // ──────────────────────────────────────────────────────────── 20 items
    'GEN-FUELTEST-QTR' => [
        ['PRE_TEST',  'ppe_worn',                 'PPE worn (gloves + eye protection)',         'CHECK',  true],
        ['PRE_TEST',  'jerry_can_ready',          'Calibrated 20-L jerry can on hand, freshly emptied', 'CHECK', true],
        ['PRE_TEST',  'gen_steady_load',          'Gen has been running at steady load for at least 5 min','CHECK',true],
        ['START',     'plc_hours_start',          'PLC run-hours at start',                     'NUMBER', true,  'hrs'],
        ['START',     'plc_load_start',           'PLC load % at start',                        'NUMBER', true,  '%'],
        ['START',     'jerry_volume_start',       'Jerry can volume at start (L)',              'NUMBER', true,  'L'],
        ['START',     'photo_plc_display_start',  'Photo: PLC display (run-hrs + load)',        'PHOTO',  true],
        ['START',     'photo_jerry_start',        'Photo: jerry can showing start volume',      'PHOTO',  true],
        ['RUN',       'gen_switched_to_jerry',    'Gen switched to jerry feed and restarted',   'CHECK',  true],
        ['RUN',       'test_duration',            'Test duration (minutes) — should be 30',     'NUMBER', true,  'min'],
        ['RUN',       'load_steady_check',        'Load remained steady (no swings > 10%)',     'CHECK',  true],
        ['END',       'plc_hours_end',            'PLC run-hours at end',                       'NUMBER', true,  'hrs'],
        ['END',       'jerry_volume_end',         'Jerry can volume at end (L)',                'NUMBER', true,  'L'],
        ['END',       'photo_plc_display_end',    'Photo: PLC display at end',                  'PHOTO',  true],
        ['END',       'photo_jerry_end',          'Photo: jerry can showing end volume',        'PHOTO',  true],
        ['RESULT',    'computed_consumption',     'Computed actual consumption (L/hr) — (start-end) × (60/min)','NUMBER',true,'L/hr'],
        ['RESULT',    'observations_notes',       'Observations / notes',                       'LONG_TEXT',false],
        ['RESTORE',   'main_tank_reconnected',    'Main tank feed reconnected, gen running normally','CHECK',true],
        ['RESTORE',   'site_secure_state',        'Site left in safe, secure state',            'CHECK',  true],
    ],

    // ──────────────────────────────────────────────────────────── 10 items
    'AC-QTR' => [
        ['CLEANING',     'clean_air_filter',        'Clean air filter',                       'CHECK',  true],
        ['CLEANING',     'clean_condenser_coils',   'Clean condenser coils',                  'CHECK',  true],
        ['CLEANING',     'check_drain_line',        'Check drain line + tray',                'CHECK',  true],
        ['CLEANING',     'fan_blades_balanced',     'Fan blades clean + balanced',            'CHECK',  true],
        ['PERFORMANCE',  'inlet_temperature',       'Inlet temperature',                      'NUMBER', true,  '°C'],
        ['PERFORMANCE',  'outlet_temperature',      'Outlet temperature',                     'NUMBER', true,  '°C'],
        ['PERFORMANCE',  'cooling_delta',           'Cooling delta (inlet − outlet)',         'NUMBER', true,  '°C'],
        ['PERFORMANCE',  'compressor_noise_check',  'Compressor noise check',                 'CHECK',  true],
        ['PHOTOS',       'ac_before_maintenance',   'AC unit before maintenance',             'PHOTO',  true],
        ['PHOTOS',       'ac_after_maintenance',    'AC unit after maintenance',              'PHOTO',  true],
    ],

    // ──────────────────────────────────────────────────────────── 10 items
    'BATT-SEMI' => [
        ['VISUAL',      'visual_swelling',            'Visual swelling check',                'CHECK',  true],
        ['VISUAL',      'visual_leak',                'Visual leak check',                    'CHECK',  true],
        ['VISUAL',      'corrosion_check',            'Corrosion check',                      'CHECK',  true],
        ['ELECTRICAL',  'total_bank_voltage',         'Total bank voltage',                   'NUMBER', true,  'V'],
        ['ELECTRICAL',  'average_cell_voltage',       'Average cell voltage',                 'NUMBER', true,  'V'],
        ['ELECTRICAL',  'terminal_torque_check',      'Terminal torque check',                'CHECK',  true],
        ['ELECTRICAL',  'connections_clean_greased',  'Connections clean + greased',          'CHECK',  true],
        ['ELECTRICAL',  'electrolyte_level',          'Electrolyte level (lead-acid only)',   'CHECK',  false],
        ['LOAD_TEST',   'load_test_current',          'Load test current',                    'NUMBER', false, 'A'],
        ['PHOTOS',      'battery_bank_overview',      'Battery bank overview',                'PHOTO',  true],
    ],

    // ──────────────────────────────────────────────────────────── 9 items
    'SHELTER-ANNUAL' => [
        ['STRUCTURE',  'roof_seal_no_leaks',           'Roof seal / no leaks',               'CHECK',  true],
        ['STRUCTURE',  'wall_cracks',                  'Wall cracks',                        'CHECK',  true],
        ['STRUCTURE',  'floor_cracks',                 'Floor cracks',                       'CHECK',  true],
        ['STRUCTURE',  'door_hinges_seals',            'Door hinges + seals',                'CHECK',  true],
        ['SYSTEMS',    'lighting_working',             'Lighting working',                   'CHECK',  true],
        ['SYSTEMS',    'ventilation_working',          'Ventilation working',                'CHECK',  true],
        ['SYSTEMS',    'fire_detection_suppression',   'Fire detection / suppression check', 'CHECK',  true],
        ['PHOTOS',     'shelter_exterior',             'Shelter exterior',                   'PHOTO',  true],
        ['PHOTOS',     'shelter_interior',             'Shelter interior',                   'PHOTO',  true],
    ],

    // ──────────────────────────────────────────────────────────── 8 items
    'CALLOUT-EMERGENCY' => [
        ['DISPATCH',    'issue_category',             'Issue category',                     'DROPDOWN', true, null, '{"choices":["POWER","GEN","BATTERY","COOLING","COMMS","ENVIRONMENT","SECURITY","OTHER"]}'],
        ['DISPATCH',    'issue_description',          'Issue description',                  'LONG_TEXT',true],
        ['ONSITE',      'response_minutes',           'Response time (minutes)',            'NUMBER',   true, 'min'],
        ['ONSITE',      'gps_arrival',                'GPS on arrival',                     'GPS',      true],
        ['ONSITE',      'photo_scene',                'Scene photo',                        'PHOTO',    true],
        ['ACTION',      'actions_taken',              'Actions taken (root cause + fix)',   'LONG_TEXT',true],
        ['ACTION',      'resolution_status',          'Resolution status',                  'DROPDOWN', true, null, '{"choices":["FIXED","MONITORING","PENDING_SPARES","PENDING_FOLLOWUP","ESCALATED"]}'],
        ['CLOSEOUT',    'photo_final',                'Final state photo',                  'PHOTO',    true],
    ],
];

/* Callout resolution templates (18 rows — mirror sitetracker16 patterns).
   Slug maps: CALLOUT-RES-GEN-FUEL/CALLOUT-RES-BATT-LOW/CALLOUT-RES-AC-CLEAN in our catalog
   are UI aliases; the concrete resolution rows live in this table by category. */
$CALLOUT_RES = [
    // POWER (3)
    ['GRID_OUTAGE_RESTORED',         'POWER',       'Grid outage restored',                'TANESCO outage confirmed',                        'Rectifier online, load transferred to grid', 'FIXED',            10],
    ['LOW_GRID_VOLT_PENDING',        'POWER',       'Low grid voltage (utility)',          'Utility supplying below tolerance',              'Pending TT follow-up with TANESCO',           'PENDING_FOLLOWUP', 20],
    ['MAINS_MCB_TRIPPED',            'POWER',       'Mains MCB tripped',                   'Transient overload / lightning',                 'Reset MCB + verify load',                     'MONITORING',       30],
    // GEN (7)
    ['GEN_OUT_OF_FUEL_REFUELED',     'GEN',         'Genset out of fuel — refueled',       'Fuel consumption higher than planned',           'Refueled to full, restarted',                 'FIXED',            40],
    ['GEN_LOW_OIL_TOPPED',           'GEN',         'Low oil — topped up',                 'Oil consumption above spec',                     'Topped up, monitoring next 100h',             'MONITORING',       50],
    ['GEN_COOLANT_TOPUP',            'GEN',         'Coolant low — topped up',             'Slow coolant loss',                              'Topped up, watching for leaks',               'MONITORING',       60],
    ['GEN_OVERHEAT_CLEAN_RAD',       'GEN',         'Overheat — radiator cleaned',         'Radiator clogged with dust / debris',            'Cleaned radiator fins, restarted',            'FIXED',            70],
    ['GEN_PLC_SENSOR_FAULT',         'GEN',         'PLC sensor fault — replaced',         'Faulty temperature / oil-pressure sensor',       'Replaced sensor, cleared alarm',              'FIXED',            80],
    ['GEN_STARTER_BAT_FLAT',         'GEN',         'Starter battery flat',                'Battery aged / not held charge',                 'Charged; needs replacement',                  'PENDING_SPARES',   90],
    ['GEN_MECH_ESCALATE',            'GEN',         'Mechanical fault — escalated',        'Beyond FS scope',                                'Escalated to workshop for pickup',            'ESCALATED',       100],
    // BATTERY (3)
    ['BAT_LOW_VOLT_GEN_RUNNING',     'BATTERY',     'Battery low voltage — gen running',   'Grid outage exceeded autonomy',                  'Genset started, charge cycle initiated',      'MONITORING',      110],
    ['BAT_CELL_DEAD_ISOLATE',        'BATTERY',     'Dead cell isolated',                  'Failed cell (age)',                              'Isolated failed cell; bank derated',          'PENDING_SPARES',  120],
    ['BAT_TERMINAL_TIGHTEN',         'BATTERY',     'Loose terminal — tightened',          'Vibration loosened lug',                         'Tightened to torque spec, greased',           'FIXED',           130],
    // COOLING (2)
    ['COOL_AC_CLEAN_FILTER',         'COOLING',     'AC weak cooling — filter cleaned',    'Filter maintenance overdue',                     'Cleaned filters + wiped evaporator',          'FIXED',           140],
    ['COOL_AC_FAILED',               'COOLING',     'AC unit failed',                      'Compressor failure suspected',                   'Escalated for replacement',                   'ESCALATED',       150],
    // COMMS (3)
    ['COMMS_TX_POWER_CYCLE',         'COMMS',       'TX dropped — power cycled',           'Transient equipment lock-up',                    'Power-cycled TX, link restored',              'FIXED',           160],
    ['COMMS_MW_FADE_WEATHER',        'COMMS',       'MW link fade (weather)',              'Rain / atmospheric fade',                        'Confirmed link restored after event',         'FIXED',           170],
    ['COMMS_FIBER_CUT',              'COMMS',       'Fibre cut',                           'Third-party cable damage',                       'Escalated to OSP team',                       'ESCALATED',       180],
    // ENVIRONMENT (3)
    ['ENV_DOOR_LEFT_OPEN',           'ENVIRONMENT', 'Door left open',                      'Previous crew failed to close',                  'Closed + locked; briefed FS crew',            'FIXED',           190],
    ['ENV_LIGHTNING_SURGE',          'ENVIRONMENT', 'Lightning surge (arrestor)',          'Storm-driven surge',                             'Isolated affected panel, arrestor spent',     'PENDING_SPARES',  200],
    ['ENV_SHELTER_FLOODING',         'ENVIRONMENT', 'Shelter flooding',                    'Heavy rain, drain blocked',                      'Drained + cleared blockage',                  'PENDING_FOLLOWUP',210],
];

/* ── Seed templates items ─────────────────────────────────────────── */
$totalItems = 0;
foreach ($TEMPLATES as $slug => $items) {
    $tplRs = $db->mySelect("SELECT c0d FROM service_templates_catalog WHERE slug = :s", [':s' => $slug]);
    if (empty($tplRs)) { echo "  ⚠ template '{$slug}' not in catalog — skipped.\n"; continue; }
    $tid = (int)$tplRs[0]['c0d'];
    // Wipe + re-insert — templates are code-owned, evolving them means a re-seed
    $db->insertUpdate("DELETE FROM service_template_items WHERE template_id = :t", [':t' => $tid]);
    $sort = 10;
    foreach ($items as $it) {
        [$section, $slugField, $label, $type, $required] = array_pad($it, 5, null);
        $unit    = $it[5] ?? null;
        $cfg     = $it[6] ?? null;
        $depSlug = $it[7] ?? null;
        $depVal  = $it[8] ?? null;
        $db->insertUpdate(
            "INSERT INTO service_template_items
                (template_id, section, sort_order, field_slug, field_label, field_type,
                 is_required, unit_or_note, config_json, depends_on_slug, depends_on_value)
             VALUES (:t, :sec, :so, :fs, :fl, :ft, :req, :u, :cfg, :ds, :dv)",
            [
                ':t' => $tid, ':sec' => $section, ':so' => $sort, ':fs' => $slugField,
                ':fl' => $label, ':ft' => $type, ':req' => $required ? 1 : 0,
                ':u' => $unit, ':cfg' => $cfg, ':ds' => $depSlug, ':dv' => $depVal,
            ]
        );
        $sort += 10;
        $totalItems++;
    }
    // Update item_count on the catalog row
    $db->insertUpdate("UPDATE service_templates_catalog SET item_count = :c WHERE c0d = :t", [':c' => count($items), ':t' => $tid]);
    echo "  ✓ {$slug} → " . count($items) . " items\n";
}

/* ── Seed callout resolutions ─────────────────────────────────────── */
$db->insertUpdate("TRUNCATE TABLE service_callout_resolutions_catalog", []);
foreach ($CALLOUT_RES as $r) {
    [$code, $cat, $title, $rc, $act, $status, $order] = $r;
    $db->insertUpdate(
        "INSERT INTO service_callout_resolutions_catalog
            (code, category, title, root_cause, action_taken, fault_status, sort_order)
         VALUES (:c, :cat, :t, :rc, :a, :s, :o)",
        [':c' => $code, ':cat' => $cat, ':t' => $title, ':rc' => $rc, ':a' => $act, ':s' => $status, ':o' => $order]
    );
}
echo "  ✓ " . count($CALLOUT_RES) . " callout resolution patterns\n";

echo "\n=== DONE · {$totalItems} template items + " . count($CALLOUT_RES) . " callout resolutions seeded ===\n";
