<?php
// 2025-09-10-031020_CreateFamilyStudents.php
namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

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

    public function up()
    {
        if (! $this->db->tableExists('families') || ! $this->db->tableExists('students')) {
            throw new \RuntimeException('CreateFamilyStudents requires families and students tables to exist.');
        }

        $this->forge->addField([
            'id'              => ['type'=>'INT','unsigned'=>true,'auto_increment'=>true],
            'family_id'       => ['type'=>'INT','unsigned'=>true,'null'=>false],
            'student_id'      => ['type'=>'INT','unsigned'=>true,'null'=>false],
            'is_primary_home' => ['type'=>'TINYINT','constraint'=>1,'default'=>1],
            'notes'           => ['type'=>'VARCHAR','constraint'=>255,'null'=>true],
        ]);
        $this->forge->addKey('id', true);
        $this->forge->addUniqueKey(['family_id','student_id'], 'uq_family_student');
        $this->forge->addKey('student_id'); // no name param
        $this->forge->addForeignKey('family_id','families','id','CASCADE','CASCADE','fk_fs_family');
        $this->forge->addForeignKey('student_id','students','id','CASCADE','CASCADE','fk_fs_student');

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

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