<?php
declare(strict_types=1);

use Phinx\Migration\AbstractMigration;

/**
 * Turn PM template tasks into a real form-builder + seed a plant-oriented
 * template library. Also carry richer per-task responses on work orders.
 *
 * Schema additions:
 *   pm_template_tasks +input_type +options_json +is_required
 *   work_order_tasks  +response_value +remedy_note
 *
 * Seeds 15 templates × ~120 tasks covering: generator PM cycles, aircon,
 * transformer, stabilizer/UPS, panel switchgear, motor starter, plus
 * cross-cutting safety (fire extinguisher, grounding, power sweep).
 */
final class PmFormFieldsAndSeed extends AbstractMigration
{
    public function up(): void
    {
        // ── 1. Schema tweaks ────────────────────────────────────────────
        $this->table('pm_template_tasks')
            ->addColumn('input_type',   'string',  ['limit' => 20, 'default' => 'checkbox', 'after' => 'description']) // checkbox|options|number|text|photo
            ->addColumn('options_json', 'text',    ['null' => true, 'after' => 'input_type'])
            ->addColumn('is_required',  'boolean', ['default' => false, 'after' => 'options_json'])
            ->update();

        $this->table('work_order_tasks')
            ->addColumn('input_type',     'string', ['limit' => 20,  'default' => 'checkbox', 'after' => 'description'])
            ->addColumn('options_json',   'text',   ['null' => true, 'after' => 'input_type'])
            ->addColumn('is_required',    'boolean',['default' => false, 'after' => 'options_json'])
            ->addColumn('response_value', 'string', ['limit' => 120, 'null' => true, 'after' => 'result_note'])
            ->addColumn('remedy_note',    'text',   ['null' => true, 'after' => 'response_value'])
            ->update();

        // ── 2. Seed templates ───────────────────────────────────────────
        $tenantId = (int) $this->fetchRow(
            "SELECT tenant_id FROM tenants WHERE subdomain = 'orchid' LIMIT 1"
        )['tenant_id'];

        $typeIdOf = function (string $code) use ($tenantId): ?int {
            $row = $this->fetchRow(
                "SELECT asset_type_id FROM asset_types WHERE tenant_id = {$tenantId} AND code = '{$code}' LIMIT 1"
            );
            return $row ? (int) $row['asset_type_id'] : null;
        };

        $genId    = $typeIdOf('generator');
        $acId     = $typeIdOf('aircon');
        $trafoId  = $typeIdOf('transformer');
        $stabId   = $typeIdOf('stabilizer');
        $panelId  = $typeIdOf('panel');
        $motorId  = $typeIdOf('motor_starter');

        // Reusable option lists.
        $CHECKED     = json_encode(['CHECKED','NOT CHECKED']);
        $OK_HIGH_LOW = json_encode(['OK','HIGH','LOW']);
        $OK_NOT      = json_encode(['OK','NOT OK']);
        $PASS_FAIL   = json_encode(['PASS','FAIL','NOT APPLICABLE']);

        $templates = [
            [
                'code' => 'daily_gen_check',
                'name' => 'Daily Generator Checklist',
                'description' => "Daily walk-around and readings for standby generators.",
                'asset_type_id' => $genId,
                'interval_days' => 1, 'lead_days' => 0, 'priority' => 'medium',
                'tasks' => [
                    ['Check engine oil level',                       'options', $OK_HIGH_LOW, true],
                    ['Check coolant level',                          'options', $OK_HIGH_LOW, true],
                    ['Check fuel level (record %)',                  'number',  null, true],
                    ['Record generator hours',                       'number',  null, true],
                    ['Check for oil / fuel / coolant leaks',         'options', $CHECKED,     true],
                    ['Check battery terminals + electrolyte',        'options', $OK_NOT,      true],
                    ['Inspect belts + hoses for cracks',             'options', $CHECKED,     false],
                    ['Check exhaust for unusual smoke',              'options', $CHECKED,     false],
                    ['Verify AVR / control panel indicators',        'options', $OK_NOT,      true],
                    ['Photograph fuel gauge + hour meter',           'photo',   null,         false],
                ],
            ],
            [
                'code' => 'weekly_gen_load_test',
                'name' => 'Weekly Generator Load Test',
                'description' => "No-break load test to verify generator can carry site load.",
                'asset_type_id' => $genId,
                'interval_days' => 7, 'lead_days' => 1, 'priority' => 'medium',
                'tasks' => [
                    ['Confirm ATS in AUTO mode',                     'options', $OK_NOT,   true],
                    ['Simulate mains failure via test switch',       'checkbox',null,       true],
                    ['Record start-up time (seconds)',               'number',  null,       true],
                    ['Record voltage L1/L2/L3 under load',           'text',    null,       true],
                    ['Record frequency under load',                  'number',  null,       true],
                    ['Restore mains + confirm ATS returns to normal','checkbox',null,       true],
                ],
            ],
            [
                'code' => 'gen_250h_service',
                'name' => '250-hr Generator Oil & Filter Service',
                'description' => "Minor service — oil, oil filter, visual belts.",
                'asset_type_id' => $genId,
                'interval_days' => 30, 'lead_days' => 5, 'priority' => 'high',
                'tasks' => [
                    ['Isolate generator (LOTO)',                     'checkbox',null,       true],
                    ['Drain engine oil (record litres)',             'number',  null,       true],
                    ['Replace oil filter (record part number)',      'text',    null,       true],
                    ['Refill with correct grade oil',                'text',    null,       true],
                    ['Check air filter, clean or replace',           'options', json_encode(['CLEANED','REPLACED','OK AS-IS']), true],
                    ['Check + tighten hose clamps',                  'options', $OK_NOT,    true],
                    ['Run engine + verify no leaks',                 'options', $OK_NOT,    true],
                    ['Reset service-hour counter',                   'checkbox',null,       false],
                ],
            ],
            [
                'code' => 'gen_500h_service',
                'name' => '500-hr Generator Full Service',
                'description' => "Major PM including fuel filters, air filter, coolant test.",
                'asset_type_id' => $genId,
                'interval_days' => 60, 'lead_days' => 7, 'priority' => 'high',
                'tasks' => [
                    ['Isolate generator (LOTO)',                     'checkbox',null,       true],
                    ['Drain + refill engine oil (litres)',           'number',  null,       true],
                    ['Replace oil filter',                           'checkbox',null,       true],
                    ['Replace primary fuel filter',                  'checkbox',null,       true],
                    ['Replace secondary fuel filter',                'checkbox',null,       true],
                    ['Replace air filter',                           'checkbox',null,       true],
                    ['Test coolant SCA + freeze point',              'options', $PASS_FAIL, true],
                    ['Inspect belts + tension',                      'options', $OK_NOT,    true],
                    ['Inspect radiator + clean fins',                'options', $OK_NOT,    true],
                    ['Battery: check + top up electrolyte',          'options', $OK_NOT,    true],
                    ['Load-test 30 min at ≥75% rated',               'options', $PASS_FAIL, true],
                    ['Photograph completed work',                    'photo',   null,       false],
                ],
            ],
            [
                'code' => 'gen_annual_service',
                'name' => 'Annual Generator Major Service',
                'description' => "Comprehensive annual overhaul-adjacent PM.",
                'asset_type_id' => $genId,
                'interval_days' => 365, 'lead_days' => 14, 'priority' => 'high',
                'tasks' => [
                    ['Isolate generator (LOTO) + tag',               'checkbox',null,       true],
                    ['Full oil + all filters change',                'checkbox',null,       true],
                    ['Coolant flush + refill',                       'checkbox',null,       true],
                    ['Replace all rubber hoses if aged >5 yr',       'options', json_encode(['REPLACED','KEPT']), true],
                    ['Replace belts',                                'checkbox',null,       true],
                    ['Injector inspection / test',                   'options', $PASS_FAIL, true],
                    ['Valve clearance check + adjust',               'options', $PASS_FAIL, true],
                    ['Alternator brush inspection',                  'options', $OK_NOT,    true],
                    ['AVR calibration',                              'options', $PASS_FAIL, true],
                    ['Full electrical safety test (megger)',         'options', $PASS_FAIL, true],
                    ['ATS full function test',                       'options', $PASS_FAIL, true],
                    ['Enclosure paint + rust check',                 'options', $OK_NOT,    false],
                    ['Update service log + labels',                  'checkbox',null,       true],
                    ['Load-test 2 hrs at ≥80% rated',                'options', $PASS_FAIL, true],
                    ['Photograph identification plate + hour meter', 'photo',   null,       true],
                ],
            ],
            [
                'code' => 'daily_power_sweep',
                'name' => 'Daily Power, Lighting & Grounding Sweep',
                'description' => "General plant walk-through for power, consumables, lighting, grounding.",
                'asset_type_id' => null,
                'interval_days' => 1, 'lead_days' => 0, 'priority' => 'medium',
                'tasks' => [
                    ['Check for faulty lighting (lamp/ballast/starter)',     'options', $CHECKED, true],
                    ['Check for deteriorated light output',                  'options', $CHECKED, true],
                    ['Observe energy saving (lights off during day)',        'options', $CHECKED, true],
                    ['Observe cable safety (torn / exposed)',                'options', $OK_NOT,  true],
                    ['Verify power supply stability',                        'options', $OK_NOT,  true],
                    ['Check voltage consistency',                            'options', $OK_HIGH_LOW, true],
                    ['Check for unusual smell / noise from panels',          'options', $CHECKED, true],
                    ['Check for loose connections in accessible panels',     'options', $OK_NOT,  true],
                    ['Verify emergency lighting operates',                   'options', $PASS_FAIL, true],
                    ['Ground / earth strap continuity check',                'options', $PASS_FAIL, true],
                ],
            ],
            [
                'code' => 'monthly_ac_check',
                'name' => 'Monthly AC Filter & Coil Check',
                'description' => "Basic monthly PM for split / package aircons.",
                'asset_type_id' => $acId,
                'interval_days' => 30, 'lead_days' => 3, 'priority' => 'medium',
                'tasks' => [
                    ['Clean or replace filter',                              'options', json_encode(['CLEANED','REPLACED']), true],
                    ['Inspect + clean condenser coil',                       'options', $OK_NOT,   true],
                    ['Check indoor drain (blockage)',                        'options', $OK_NOT,   true],
                    ['Record suction + discharge pressures',                 'text',    null,      true],
                    ['Record supply air temp (°C)',                          'number',  null,      true],
                    ['Check thermostat setpoint',                            'text',    null,      false],
                    ['Photograph coils after cleaning',                     'photo',   null,      false],
                ],
            ],
            [
                'code' => 'annual_ac_compressor_service',
                'name' => 'Annual AC Compressor Service',
                'description' => "Full annual PM including refrigerant + electrical.",
                'asset_type_id' => $acId,
                'interval_days' => 365, 'lead_days' => 14, 'priority' => 'high',
                'tasks' => [
                    ['Isolate power + tag',                                  'checkbox',null,       true],
                    ['Check + top up refrigerant',                           'options', json_encode(['TOPPED-UP','OK','LEAK FOUND']), true],
                    ['Leak test all joints',                                 'options', $PASS_FAIL, true],
                    ['Clean condenser + evaporator coils',                   'checkbox',null,       true],
                    ['Check compressor oil level',                           'options', $OK_HIGH_LOW, true],
                    ['Insulation resistance test on compressor motor',      'options', $PASS_FAIL, true],
                    ['Tighten electrical terminations',                     'checkbox',null,       true],
                    ['Inspect + replace contactor if pitted',                'options', json_encode(['OK','REPLACED']), true],
                    ['Vibration + noise check',                              'options', $OK_NOT,    true],
                    ['Test run + record temperatures',                       'text',    null,       true],
                ],
            ],
            [
                'code' => 'monthly_transformer',
                'name' => 'Monthly Transformer Inspection',
                'description' => "Visual + basic readings on distribution transformer.",
                'asset_type_id' => $trafoId,
                'interval_days' => 30, 'lead_days' => 3, 'priority' => 'high',
                'tasks' => [
                    ['Oil level in main tank (record)',                      'options', $OK_HIGH_LOW, true],
                    ['Silica gel breather colour (blue = ok)',               'options', json_encode(['BLUE','PINK','WHITE']), true],
                    ['Check for leaks on bushings + gaskets',                'options', $CHECKED,     true],
                    ['Record oil temperature (°C)',                          'number',  null,         true],
                    ['Record winding temperature (°C) if fitted',            'number',  null,         false],
                    ['Bushing condition (chips / tracking)',                 'options', $OK_NOT,      true],
                    ['Fence + earthing intact',                              'options', $OK_NOT,      true],
                    ['Photograph nameplate + gauges',                        'photo',   null,         false],
                ],
            ],
            [
                'code' => 'annual_transformer_dga',
                'name' => 'Annual Transformer DGA Oil Sampling',
                'description' => "Dissolved Gas Analysis to spot faults early.",
                'asset_type_id' => $trafoId,
                'interval_days' => 365, 'lead_days' => 30, 'priority' => 'medium',
                'tasks' => [
                    ['De-energise + LOTO transformer',                       'checkbox',null,     true],
                    ['Draw oil sample using approved bottle',                'checkbox',null,     true],
                    ['Record sample bottle ID',                              'text',    null,     true],
                    ['Send to lab (record dispatch date)',                   'text',    null,     true],
                    ['Attach lab report to WO when returned',                'photo',   null,     true],
                ],
            ],
            [
                'code' => 'monthly_ups_battery',
                'name' => 'Monthly UPS / Stabilizer Battery Check',
                'description' => "Battery bank health for standby power.",
                'asset_type_id' => $stabId,
                'interval_days' => 30, 'lead_days' => 3, 'priority' => 'high',
                'tasks' => [
                    ['Record float voltage per string',                      'text',    null,      true],
                    ['Measure ambient temperature',                          'number',  null,      true],
                    ['Check for corrosion on terminals',                     'options', $OK_NOT,   true],
                    ['Check ventilation intake / exhaust',                   'options', $OK_NOT,   true],
                    ['Verify alarms + display panel',                        'options', $OK_NOT,   true],
                    ['Photograph any bulged / leaking battery',              'photo',   null,      false],
                ],
            ],
            [
                'code' => 'q_panel_thermographic',
                'name' => 'Quarterly Panel Thermographic Scan',
                'description' => "IR camera scan to find hotspots before failure.",
                'asset_type_id' => $panelId,
                'interval_days' => 90, 'lead_days' => 7, 'priority' => 'high',
                'tasks' => [
                    ['Confirm load is normal / above 40%',                   'options', $OK_NOT,    true],
                    ['Scan all incoming/outgoing terminations',              'checkbox',null,       true],
                    ['Record max temperature hotspot (°C)',                  'number',  null,       true],
                    ['Attach thermal image of any hotspot >60°C above ambient','photo', null,       false],
                    ['Compare against previous scan (delta)',                'text',    null,       false],
                ],
            ],
            [
                'code' => 'q_motor_vibration',
                'name' => 'Quarterly Motor Vibration Analysis',
                'description' => "Detects bearing wear + shaft misalignment early.",
                'asset_type_id' => $motorId,
                'interval_days' => 90, 'lead_days' => 7, 'priority' => 'medium',
                'tasks' => [
                    ['Verify motor is running under normal load',            'options', $OK_NOT,   true],
                    ['Vibration reading — drive-end bearing (mm/s)',        'number',  null,      true],
                    ['Vibration reading — non-drive-end bearing (mm/s)',    'number',  null,      true],
                    ['Bearing temperature — drive end (°C)',                'number',  null,      true],
                    ['Bearing temperature — non-drive end (°C)',            'number',  null,      true],
                    ['Overall recommendation',                              'options', json_encode(['CONTINUE','MONITOR','SCHEDULE REPAIR','URGENT']), true],
                ],
            ],
            [
                'code' => 'weekly_fire_extinguisher',
                'name' => 'Weekly Fire Extinguisher Inspection',
                'description' => "Regulatory visual check on plant fire extinguishers.",
                'asset_type_id' => null,
                'interval_days' => 7, 'lead_days' => 1, 'priority' => 'high',
                'tasks' => [
                    ['Pressure gauge in green band',                         'options', $OK_NOT,    true],
                    ['Seal + tamper pin intact',                             'options', $OK_NOT,    true],
                    ['No visible damage / rust',                             'options', $OK_NOT,    true],
                    ['Service label current (< 12 months)',                  'options', $PASS_FAIL, true],
                    ['Mounting bracket + signage present',                   'options', $OK_NOT,    true],
                ],
            ],
            [
                'code' => 'monthly_grounding_earth',
                'name' => 'Monthly Grounding & Earth Resistance',
                'description' => "Verify earth pit resistance + strap continuity.",
                'asset_type_id' => null,
                'interval_days' => 30, 'lead_days' => 5, 'priority' => 'high',
                'tasks' => [
                    ['Visual: earth pit cover + strap intact',               'options', $OK_NOT,    true],
                    ['Water top-up in earth pit if required',                'options', json_encode(['DONE','NOT NEEDED']), true],
                    ['Earth resistance value (Ω) — target <5',               'number',  null,       true],
                    ['Body-to-earth continuity on equipment sampled',       'options', $PASS_FAIL, true],
                    ['Photograph earth pit + reading',                       'photo',   null,       false],
                ],
            ],
        ];

        foreach ($templates as $tpl) {
            $templateId = (int) $this->getAdapter()->getConnection()->query(
                "SELECT template_id FROM pm_templates WHERE tenant_id = {$tenantId} AND code = " .
                $this->getAdapter()->getConnection()->quote($tpl['code']) . " LIMIT 1"
            )->fetchColumn();

            if (!$templateId) {
                $this->table('pm_templates')->insert([
                    'tenant_id'     => $tenantId,
                    'asset_type_id' => $tpl['asset_type_id'],
                    'code'          => $tpl['code'],
                    'name'          => $tpl['name'],
                    'description'   => $tpl['description'],
                    'interval_days' => $tpl['interval_days'],
                    'lead_days'     => $tpl['lead_days'],
                    'priority'      => $tpl['priority'],
                    'is_active'     => 1,
                ])->saveData();
                $templateId = (int) $this->getAdapter()->getConnection()->query(
                    "SELECT template_id FROM pm_templates WHERE tenant_id = {$tenantId} AND code = " .
                    $this->getAdapter()->getConnection()->quote($tpl['code']) . " LIMIT 1"
                )->fetchColumn();
            }

            foreach ($tpl['tasks'] as $i => $t) {
                [$title, $inputType, $options, $required] = $t;
                $this->table('pm_template_tasks')->insert([
                    'template_id'  => $templateId,
                    'sort_order'   => ($i + 1) * 10,
                    'title'        => $title,
                    'description'  => null,
                    'input_type'   => $inputType,
                    'options_json' => $options,
                    'is_required'  => $required ? 1 : 0,
                ])->saveData();
            }
        }
    }

    public function down(): void
    {
        // Remove seeded templates (keeps user-created templates intact)
        $codes = [
            'daily_gen_check','weekly_gen_load_test','gen_250h_service','gen_500h_service','gen_annual_service',
            'daily_power_sweep','monthly_ac_check','annual_ac_compressor_service','monthly_transformer',
            'annual_transformer_dga','monthly_ups_battery','q_panel_thermographic','q_motor_vibration',
            'weekly_fire_extinguisher','monthly_grounding_earth',
        ];
        $codeList = "'" . implode("','", $codes) . "'";
        $this->execute("DELETE FROM pm_templates WHERE code IN ({$codeList})");

        $this->table('pm_template_tasks')
            ->removeColumn('input_type')
            ->removeColumn('options_json')
            ->removeColumn('is_required')
            ->update();
        $this->table('work_order_tasks')
            ->removeColumn('response_value')
            ->removeColumn('remedy_note')
            ->update();
    }
}
