<?php
// 2025-09-10-031040_CreateCommunicationLogs.php
namespace App\Database\Migrations;

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

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

    public function up()
    {
        if (! $this->db->tableExists('families')) {
            throw new \RuntimeException('CreateCommunicationLogs requires families table to exist.');
        }

        $this->forge->addField([
            'id'            => ['type'=>'BIGINT','unsigned'=>true,'auto_increment'=>true],
            'student_id'    => ['type'=>'INT','unsigned'=>true,'null'=>false],
            'family_id'     => ['type'=>'INT','unsigned'=>true,'null'=>true], // SET NULL on delete
            'student_name'  => ['type'=>'VARCHAR','constraint'=>150,'null'=>false],
            'template_key'  => ['type'=>'VARCHAR','constraint'=>64,'null'=>false],
            'subject'       => ['type'=>'VARCHAR','constraint'=>255,'null'=>false],
            'body'          => ['type'=>'MEDIUMTEXT','null'=>false],
            'recipients'    => ['type'=>'TEXT','null'=>false],
            'cc'            => ['type'=>'TEXT','null'=>true],
            'bcc'           => ['type'=>'TEXT','null'=>true],
            'attachments'   => ['type'=>'TEXT','null'=>true],
            'status'        => ['type'=>'ENUM','constraint'=>['sent','failed'],'null'=>false],
            'error_message' => ['type'=>'TEXT','null'=>true],
            'sent_by'       => ['type'=>'INT','unsigned'=>true,'null'=>true],
            'metadata'      => ['type'=>'JSON','null'=>true],
            'created_at'    => ['type'=>'DATETIME','null'=>false,'default'=>new RawSql('CURRENT_TIMESTAMP')],
        ]);
        $this->forge->addKey('id', true);
        $this->forge->addKey('student_id');
        $this->forge->addKey('family_id');
        $this->forge->addKey('template_key');
        $this->forge->addForeignKey('family_id','families','id','SET NULL','CASCADE','fk_comm_family');

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

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