<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddAttendanceDateAndUniqueToAttendanceSessionsTable extends Migration
{
    public function up()
    {
        $this->forge->addColumn('attendance_sessions', [
            'attendance_date' => [
                'type'    => 'DATE',
                'null'    => true,
                'after'   => 'schedule_id',
            ],
        ]);

        $this->db->query('UPDATE attendance_sessions SET attendance_date = DATE(checkin_at) WHERE attendance_date IS NULL');

        $this->forge->modifyColumn('attendance_sessions', [
            'attendance_date' => [
                'type'  => 'DATE',
                'null'  => false,
                'after' => 'schedule_id',
            ],
        ]);

        $prefix = $this->db->DBPrefix;
        $table  = $this->db->escapeIdentifiers($prefix . 'attendance_sessions');
        $this->db->query('ALTER TABLE ' . $table . ' ADD UNIQUE KEY unique_student_schedule_date (student_id, schedule_id, attendance_date)');
    }

    public function down()
    {
        $prefix = $this->db->DBPrefix;
        $table  = $this->db->escapeIdentifiers($prefix . 'attendance_sessions');
        $this->db->query('ALTER TABLE ' . $table . ' DROP KEY unique_student_schedule_date');
        $this->forge->dropColumn('attendance_sessions', 'attendance_date');
    }
}
