<?php
declare(strict_types=1);

use Phinx\Migration\AbstractMigration;

final class SuperAdmin extends AbstractMigration
{
    public function change(): void
    {
        // ── users: add super‑admin flag ──────────────────────────────
        $this->table('users')
            ->addColumn('is_super_admin', 'boolean', [
                'null'    => false,
                'default' => false,
                'after'   => 'role_id',
            ])
            ->update();

        // ── tenants: track who created the tenant ────────────────────
        $this->table('tenants')
            ->addColumn('created_by_super', 'integer', [
                'null'    => true,
                'default' => null,
                'after'   => 'status',
            ])
            ->update();

        // ── default_checklists (tenant_id=NULL, global templates) ────
        $tpl = $this->table('default_checklists', ['id' => 'default_checklist_id']);
        $tpl->addColumn('name', 'string', ['limit' => 200])
            ->addColumn('description', 'text', ['null' => true])
            ->addColumn('asset_type_id', 'integer', ['null' => true, 'signed' => false])
            ->addColumn('interval_days', 'integer', ['null' => true, 'default' => 30])
            ->addColumn('meter_name', 'string', ['limit' => 100, 'null' => true])
            ->addColumn('meter_interval', 'integer', ['null' => true])
            ->addColumn('estimated_minutes', 'integer', ['null' => true, 'default' => 60])
            ->addColumn('is_active', 'boolean', ['default' => true])
            ->addColumn('created_by', 'integer', ['null' => true])
            ->addColumn('created_at', 'datetime', ['default' => 'CURRENT_TIMESTAMP'])
            ->addColumn('updated_at', 'datetime', ['null' => true])
            ->addColumn('deleted_at', 'datetime', ['null' => true])
            ->create();

        // ── default_checklist_tasks ──────────────────────────────────
        $tsk = $this->table('default_checklist_tasks', ['id' => 'task_id']);
        $tsk->addColumn('default_checklist_id', 'integer', ['signed' => false])
            ->addColumn('sort_order', 'integer', ['default' => 0])
            ->addColumn('title', 'string', ['limit' => 250])
            ->addColumn('description', 'text', ['null' => true])
            ->addColumn('input_type', 'string', ['limit' => 20, 'default' => 'checkbox'])
            ->addColumn('options_json', 'text', ['null' => true])
            ->addColumn('is_required', 'boolean', ['default' => false])
            ->addColumn('photo_requirement', 'string', ['limit' => 20, 'default' => 'n_a'])
            ->addColumn('created_at', 'datetime', ['default' => 'CURRENT_TIMESTAMP'])
            ->addColumn('updated_at', 'datetime', ['null' => true])
            ->addForeignKey('default_checklist_id', 'default_checklists', 'default_checklist_id',
                ['delete' => 'CASCADE', 'update' => 'CASCADE'])
            ->create();

        // ── seed the first SuperAdmin user ───────────────────────────
        // Default password: Admin@123  (bcrypt hash)
        $this->execute("
            INSERT INTO users (tenant_id, username, f_name, l_name, password, email, role_id, is_super_admin, status, created_at)
            SELECT NULL, 'superadmin', 'Super', 'Admin', '\$2y\$10\$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'super@orchview.local', r.role_id, 1, 'active', NOW()
              FROM roles r WHERE r.tenant_id IS NULL AND r.code = 'admin'
            -- if there is already a superadmin row, skip
              AND NOT EXISTS (SELECT 1 FROM users u2 WHERE u2.username = 'superadmin' AND u2.is_super_admin = 1)
            LIMIT 1
        ");
    }
}