<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddScheduleSettings extends Migration
{
    public function up()
    {
        // Cek apakah tabel settings sudah ada
        if (!$this->db->tableExists('settings')) {
            // Buat tabel settings jika belum ada
            $this->forge->addField([
                'id' => [
                    'type'           => 'INT',
                    'unsigned'       => true,
                    'auto_increment' => true,
                ],
                'setting_key' => [
                    'type'       => 'VARCHAR',
                    'constraint' => 100,
                ],
                'setting_value' => [
                    'type'       => 'TEXT',
                    'null'       => true,
                ],
                'setting_group' => [
                    'type'       => 'VARCHAR',
                    'constraint' => 50,
                    'default'    => 'general',
                ],
                'description' => [
                    'type'       => 'VARCHAR',
                    'constraint' => 255,
                    'null'       => true,
                ],
                'created_at' => [
                    'type' => 'DATETIME',
                    'null' => true,
                ],
                'updated_at' => [
                    'type' => 'DATETIME',
                    'null' => true,
                ],
            ]);
            
            $this->forge->addKey('id', true);
            $this->forge->addUniqueKey('setting_key');
            $this->forge->createTable('settings', true);
        }

        // Insert atau update default settings (gunakan ON DUPLICATE KEY)
        $this->db->query("
            INSERT INTO `settings` (`setting_key`, `setting_value`, `setting_group`, `description`, `created_at`, `updated_at`) 
            VALUES 
                ('schedule_max_hours_per_day', '6', 'schedule', 'Batas maksimal jam mengajar guru per hari (global)', NOW(), NOW()),
                ('schedule_max_block_per_day', '3', 'schedule', 'Batas maksimal blok mengajar per hari untuk satu mapel', NOW(), NOW()),
                ('schedule_max_block_size', '3', 'schedule', 'Batas maksimal jam dalam satu blok mengajar', NOW(), NOW())
            ON DUPLICATE KEY UPDATE 
                setting_value = VALUES(setting_value),
                updated_at = NOW()
        ");
    }

    public function down()
    {
        // Hapus setting yang kita tambahkan (opsional, jangan hapus tabel)
        $this->db->query("DELETE FROM `settings` WHERE setting_key IN ('schedule_max_hours_per_day', 'schedule_max_block_per_day', 'schedule_max_block_size')");
    }
}