<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * Tabel DETAIL item bahan per transaksi pembelian.
 * Setiap transaksi (id_pembelian_bahan) bisa punya BANYAK baris di sini.
 */
class CreateTbDetailPembelianBahanTable extends Migration
{
    public function up(): void
    {
        $this->forge->addField([
            'id_detail_pembelian_bahan' => [
                'type'           => 'INT',
                'constraint'     => 11,
                'unsigned'       => true,
                'auto_increment' => true,
            ],
            // FK ke header
            'id_pembelian_bahan' => [
                'type'       => 'INT',
                'constraint' => 11,
                'unsigned'   => true,
                'null'       => false,
            ],
            // FK ke master bahan
            'id_bahan' => [
                'type'       => 'INT',
                'constraint' => 11,
                'unsigned'   => true,
                'null'       => false,
            ],
            'jumlah_bahan' => [
                'type'       => 'DECIMAL',
                'constraint' => '12,3',
                'null'       => false,
            ],
            'harga_satuan_bahan' => [
                'type'       => 'DECIMAL',
                'constraint' => '15,2',
                'null'       => false,
            ],
            // total = jumlah_bahan * harga_satuan_bahan (dihitung saat insert)
            'subtotal_bahan' => [
                'type'       => 'DECIMAL',
                'constraint' => '15,2',
                'null'       => false,
                'default'    => '0.00',
            ],
            'created_at' => ['type' => 'DATETIME', 'null' => true, 'default' => null],
            'updated_at' => ['type' => 'DATETIME', 'null' => true, 'default' => null],
        ]);

        $this->forge->addKey('id_detail_pembelian_bahan', true);
        $this->forge->addForeignKey('id_pembelian_bahan', 'tb_pembelian_bahan', 'id_pembelian_bahan', 'CASCADE', 'CASCADE');
        $this->forge->addForeignKey('id_bahan', 'tb_bahan', 'id_bahan', 'CASCADE', 'RESTRICT');
        $this->forge->createTable('tb_detail_pembelian_bahan');
    }

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