<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * CreateTbResepTable — struktur header only.
 * Bahan disimpan di tb_detail_resep (dibuat oleh migration Restrukturisasi).
 */
class CreateTbResepTable extends Migration
{
    public function up(): void
    {
        // Skip jika tabel sudah ada (misal: dijalankan setelah Restrukturisasi)
        if ($this->db->tableExists('tb_resep')) {
            return;
        }

        $this->forge->addField([
            'id_resep' => [
                'type'           => 'INT',
                'constraint'     => 11,
                'unsigned'       => true,
                'auto_increment' => true,
            ],
            'nama_resep' => [
                'type'       => 'VARCHAR',
                'constraint' => 255,
                'null'       => false,
            ],
            'id_produk' => [
                'type'       => 'INT',
                'constraint' => 11,
                'unsigned'   => true,
                'null'       => true,
                'default'    => null,
            ],
            'catatan_resep' => [
                'type'    => 'TEXT',
                'null'    => true,
                'default' => null,
            ],
            'created_at' => [
                'type'    => 'DATETIME',
                'null'    => true,
                'default' => new \CodeIgniter\Database\RawSql('CURRENT_TIMESTAMP'),
            ],
            'updated_at' => [
                'type'    => 'DATETIME',
                'null'    => true,
                'default' => new \CodeIgniter\Database\RawSql('CURRENT_TIMESTAMP'),
            ],
        ]);

        $this->forge->addKey('id_resep', true);
        $this->forge->addKey('id_produk');
        $this->forge->addForeignKey('id_produk', 'tb_produk', 'id_produk', 'SET NULL', 'CASCADE', 'fk_resep_produk');
        $this->forge->createTable('tb_resep');
    }

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