<?php
declare(strict_types=1);

use Phinx\Migration\AbstractMigration;

/**
 * Flexible asset type system:
 *   asset_types           — one row per equipment kind (Generator, Chiller, HVAC, ...)
 *   asset_type_fields     — schema definition — drives the dynamic form UI
 *
 * Field values live in assets.meta_json (JSON column). This mirrors SiteTracker16's
 * approach: EAV pain is avoided, but admins can still define custom fields per type
 * without a developer or schema change.
 */
final class CreateAssetTypes extends AbstractMigration
{
    public function change(): void
    {
        $this->table('asset_types', ['id' => 'asset_type_id', 'signed' => false])
            ->addColumn('tenant_id',   'integer', ['signed' => false])
            ->addColumn('code',        'string',  ['limit' => 40])
            ->addColumn('name',        'string',  ['limit' => 120])
            ->addColumn('description', 'text',    ['null' => true])
            ->addColumn('icon',        'string',  ['limit' => 40,  'null' => true])
            ->addColumn('color',       'string',  ['limit' => 20,  'null' => true])
            ->addColumn('sort_order',  'integer', ['default' => 0])
            ->addColumn('status',      'string',  ['limit' => 20, 'default' => 'active'])
            ->addColumn('created_by',  'integer', ['null' => true, 'signed' => false])
            ->addColumn('created_at',  'datetime',['default' => 'CURRENT_TIMESTAMP'])
            ->addColumn('updated_at',  'datetime',['default' => 'CURRENT_TIMESTAMP', 'update' => 'CURRENT_TIMESTAMP'])
            ->addColumn('deleted_at',  'datetime',['null' => true])
            ->addIndex(['tenant_id', 'code'], ['unique' => true])
            ->addIndex(['tenant_id', 'status'])
            ->addForeignKey('tenant_id',  'tenants', 'tenant_id', ['delete' => 'RESTRICT', 'update' => 'CASCADE'])
            ->addForeignKey('created_by', 'users',   'user_id',   ['delete' => 'SET_NULL', 'update' => 'CASCADE'])
            ->create();

        $this->table('asset_type_fields', ['id' => 'field_id', 'signed' => false])
            ->addColumn('asset_type_id', 'integer', ['signed' => false])
            ->addColumn('field_key',     'string',  ['limit' => 60])
            ->addColumn('field_label',   'string',  ['limit' => 120])
            ->addColumn('field_type',    'string',  ['limit' => 20]) // text|number|date|datetime|select|multiselect|textarea|boolean
            ->addColumn('field_unit',    'string',  ['limit' => 20,  'null' => true])
            ->addColumn('field_options', 'text',    ['null' => true]) // JSON array for select/multiselect
            ->addColumn('field_section', 'string',  ['limit' => 60,  'default' => 'General'])
            ->addColumn('placeholder',   'string',  ['limit' => 120, 'null' => true])
            ->addColumn('help_text',     'string',  ['limit' => 255, 'null' => true])
            ->addColumn('is_required',   'boolean', ['default' => false])
            ->addColumn('sort_order',    'integer', ['default' => 0])
            ->addColumn('created_at',    'datetime',['default' => 'CURRENT_TIMESTAMP'])
            ->addColumn('updated_at',    'datetime',['default' => 'CURRENT_TIMESTAMP', 'update' => 'CURRENT_TIMESTAMP'])
            ->addIndex(['asset_type_id', 'field_key'], ['unique' => true])
            ->addIndex(['asset_type_id', 'sort_order'])
            ->addForeignKey('asset_type_id', 'asset_types', 'asset_type_id', ['delete' => 'CASCADE', 'update' => 'CASCADE'])
            ->create();

        // Seed a starter set of asset types + fields for tenant 1 — mirrors what
        // legacy OrchView tracked (generators, aircons, etc.) so users have
        // something meaningful on day one.
        $tenantId = (int) $this->fetchRow(
            "SELECT tenant_id FROM tenants WHERE subdomain = 'orchid' LIMIT 1"
        )['tenant_id'];

        $starterTypes = [
            ['code' => 'generator',     'name' => 'Generator',      'icon' => 'bolt',       'color' => '#f59e0b', 'sort_order' => 10],
            ['code' => 'aircon',        'name' => 'Air Conditioner','icon' => 'snowflake',  'color' => '#0ea5e9', 'sort_order' => 20],
            ['code' => 'transformer',   'name' => 'Transformer',    'icon' => 'zap',        'color' => '#8b5cf6', 'sort_order' => 30],
            ['code' => 'stabilizer',    'name' => 'Stabilizer',     'icon' => 'shield',     'color' => '#22c55e', 'sort_order' => 40],
            ['code' => 'panel',         'name' => 'Panel',          'icon' => 'grid',       'color' => '#6b7280', 'sort_order' => 50],
            ['code' => 'isolator',      'name' => 'Isolator',       'icon' => 'toggle',     'color' => '#a3a3a3', 'sort_order' => 60],
            ['code' => 'motor_starter', 'name' => 'Motor Starter',  'icon' => 'play',       'color' => '#ec4899', 'sort_order' => 70],
            ['code' => 'lighting',      'name' => 'Lighting',       'icon' => 'sun',        'color' => '#facc15', 'sort_order' => 80],
            ['code' => 'scissor_lift',  'name' => 'Scissor Lift',   'icon' => 'chevron-up', 'color' => '#0891b2', 'sort_order' => 90],
        ];

        foreach ($starterTypes as $t) {
            $t['tenant_id'] = $tenantId;
            $t['status']    = 'active';
            $this->table('asset_types')->insert($t)->saveData();
        }

        // Sample field schema for Generator (per-tenant, so we scope by name+tenant)
        $genId = (int) $this->fetchRow(
            "SELECT asset_type_id FROM asset_types WHERE tenant_id = {$tenantId} AND code = 'generator' LIMIT 1"
        )['asset_type_id'];

        $genFields = [
            ['field_key' => 'kva_rating',        'field_label' => 'kVA Rating',        'field_type' => 'number',   'field_unit' => 'kVA',   'field_section' => 'Specs',       'is_required' => true,  'sort_order' => 10],
            ['field_key' => 'fuel_type',         'field_label' => 'Fuel Type',         'field_type' => 'select',   'field_options' => json_encode(['diesel','petrol','gas']), 'field_section' => 'Specs', 'sort_order' => 20],
            ['field_key' => 'manufacturer',      'field_label' => 'Manufacturer',      'field_type' => 'text',     'field_section' => 'Identification', 'sort_order' => 30],
            ['field_key' => 'model_number',      'field_label' => 'Model Number',      'field_type' => 'text',     'field_section' => 'Identification', 'sort_order' => 40],
            ['field_key' => 'commission_date',   'field_label' => 'Commissioned On',   'field_type' => 'date',     'field_section' => 'Lifecycle',      'sort_order' => 50],
            ['field_key' => 'service_hours',     'field_label' => 'Service Interval',  'field_type' => 'number',   'field_unit' => 'hrs',   'field_section' => 'Maintenance', 'sort_order' => 60],
            ['field_key' => 'tank_capacity',     'field_label' => 'Fuel Tank Capacity','field_type' => 'number',   'field_unit' => 'litres','field_section' => 'Specs',       'sort_order' => 70],
        ];
        foreach ($genFields as $f) {
            $f['asset_type_id'] = $genId;
            $this->table('asset_type_fields')->insert($f)->saveData();
        }

        // Sample field schema for Air Conditioner
        $acId = (int) $this->fetchRow(
            "SELECT asset_type_id FROM asset_types WHERE tenant_id = {$tenantId} AND code = 'aircon' LIMIT 1"
        )['asset_type_id'];

        $acFields = [
            ['field_key' => 'tonnage',           'field_label' => 'Tonnage',            'field_type' => 'number', 'field_unit' => 'TR',    'field_section' => 'Specs', 'is_required' => true, 'sort_order' => 10],
            ['field_key' => 'refrigerant',       'field_label' => 'Refrigerant',        'field_type' => 'select', 'field_options' => json_encode(['R22','R134a','R410a','R32']), 'field_section' => 'Specs', 'sort_order' => 20],
            ['field_key' => 'compressor_type',   'field_label' => 'Compressor Type',    'field_type' => 'select', 'field_options' => json_encode(['reciprocating','rotary','scroll','screw']), 'field_section' => 'Specs', 'sort_order' => 30],
            ['field_key' => 'manufacturer',      'field_label' => 'Manufacturer',       'field_type' => 'text',   'field_section' => 'Identification', 'sort_order' => 40],
            ['field_key' => 'model_number',      'field_label' => 'Model Number',       'field_type' => 'text',   'field_section' => 'Identification', 'sort_order' => 50],
            ['field_key' => 'install_date',      'field_label' => 'Installed On',       'field_type' => 'date',   'field_section' => 'Lifecycle',      'sort_order' => 60],
        ];
        foreach ($acFields as $f) {
            $f['asset_type_id'] = $acId;
            $this->table('asset_type_fields')->insert($f)->saveData();
        }
    }
}
