<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class MigrateAndDropServicesTable extends Migration
{
    public function up()
    {
        if ($this->db->tableExists('services')) {
            $legacyServices = $this->db->table('services')->get()->getResultArray();
            $existingNames = array_column($this->db->table('items')->get()->getResultArray(), 'name');

            foreach ($legacyServices as $service) {
                if (in_array($service['name'], $existingNames, true)) {
                    continue;
                }

                $this->db->table('items')->insert([
                    'name' => $service['name'],
                    'price' => $service['price'],
                    'type' => 'service',
                    'created_at' => $service['created_at'] ?? date('Y-m-d H:i:s'),
                ]);
            }

            $this->forge->dropTable('services', true);
        }
    }

    public function down()
    {
        $this->forge->addField([
            'id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'auto_increment' => true],
            'name' => ['type' => 'VARCHAR', 'constraint' => 100],
            'price' => ['type' => 'INT', 'constraint' => 11],
            'created_at' => ['type' => 'DATETIME', 'null' => true],
        ]);
        $this->forge->addKey('id', true);
        $this->forge->createTable('services');
    }
}
