<?php
// 2025-09-10-031010_CreateFamilies.php
namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;
use CodeIgniter\Database\RawSql;

class CreateFamilies extends Migration
{
    protected $DBGroup = 'default';

    public function up()
    {
        $this->forge->addField([
            'id'                       => ['type'=>'INT','unsigned'=>true,'auto_increment'=>true],
            'family_code'              => ['type'=>'VARCHAR','constraint'=>32,'null'=>true],
            'household_name'           => ['type'=>'VARCHAR','constraint'=>120,'null'=>true],
            'address_line1'            => ['type'=>'VARCHAR','constraint'=>150,'null'=>true],
            'address_line2'            => ['type'=>'VARCHAR','constraint'=>150,'null'=>true],
            'city'                     => ['type'=>'VARCHAR','constraint'=>80,'null'=>true],
            'state'                    => ['type'=>'VARCHAR','constraint'=>40,'null'=>true],
            'postal_code'              => ['type'=>'VARCHAR','constraint'=>20,'null'=>true],
            'country'                  => ['type'=>'VARCHAR','constraint'=>2,'null'=>true],
            'primary_phone'            => ['type'=>'VARCHAR','constraint'=>40,'null'=>true],
            'preferred_lang'           => ['type'=>'VARCHAR','constraint'=>10,'default'=>'en','null'=>false],
            'preferred_contact_method' => ['type'=>'ENUM','constraint'=>['email','sms','phone'],'default'=>'email','null'=>false],
            'is_active'                => ['type'=>'TINYINT','constraint'=>1,'default'=>1,'null'=>false],
            'created_at'               => ['type'=>'DATETIME','null'=>false,'default'=>new RawSql('CURRENT_TIMESTAMP')],
            'updated_at'               => ['type'=>'DATETIME','null'=>false,'default'=>new RawSql('CURRENT_TIMESTAMP')],
        ]);
        $this->forge->addKey('id', true);
        $this->forge->addUniqueKey('family_code');

        $this->forge->createTable('families', true, [
            'ENGINE'=>'InnoDB','DEFAULT CHARSET'=>'utf8mb4','COLLATE'=>'utf8mb4_unicode_ci',
        ]);

        $this->db->query("ALTER TABLE `families`
            MODIFY `updated_at` DATETIME NOT NULL
            DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP");
    }

    public function down()
    {
        $this->forge->dropTable('families', true);
    }
}
