<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class Whacenter extends Migration
{
    public function up()
    {

        $fields = [
            'id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'auto_increment' => true],
            'device_id' => ['type' => 'CHAR', 'constraint' => 64, 'unique' => true],
            'nama' => ['type' => 'VARCHAR',  'constraint' => 255, 'default' => null],
            'nomor' => ['type' => 'CHAR', 'constraint' => 15, 'unique' => true],
            'is_default' => ['type' => 'ENUM',  'constraint' => ['1', '0'], 'default' => '0'],
            'is_connected' => ['type' => 'ENUM',  'constraint' => ['1', '0'], 'default' => '0'],
            'status' => ['type' => 'ENUM',  'constraint' => ['1', '0'], 'default' => '0'],
            'updated_at' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true],
            'created_at' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true],
        ];
        $this->forge->addField($fields);
        $this->forge->addKey('id', true);
        $this->forge->createTable('whatsapp_device', true);

        $fields = [
            'id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'auto_increment' => true],
            'user_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => true],
            'device_id' => ['type' => 'INT',  'constraint' => 11, 'unsigned' => true],
            'nomor' => ['type' => 'CHAR', 'constraint' => 15],
            'message' => ['type' => 'TEXT', 'null' => true],
            'updated_at' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true],
            'created_at' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true],
        ];
        $this->forge->addField($fields);
        $this->forge->addKey('id', true);
        $this->forge->addForeignKey('user_id', 'users', 'id', false, 'CASCADE');
        $this->forge->addForeignKey('device_id', 'whatsapp_device', 'id', false, 'CASCADE');
        $this->forge->createTable('whatsapp_message', true);
    }

    public function down()
    {
        // drop constraints first to prevent errors
        if ($this->db->DBDriver != 'SQLite3') {
            $this->forge->dropForeignKey('whatsapp_message', 'whatsapp_message_device_id_foreign');
            $this->forge->dropForeignKey('whatsapp_message', 'whatsapp_message_user_id_foreign');
        }
        $this->forge->dropTable('whatsapp_message', true);
        $this->forge->dropTable('whatsapp_device', true);
    }
}
