<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddPurchasePriceToBarangMasukDetail extends Migration
{
    public function up()
    {
        $this->forge->addColumn('barang', [
            'harga_beli_awal' => [
                'type'       => 'DECIMAL',
                'constraint' => '15,2',
                'default'    => 0,
                'after'      => 'harga_beli',
            ],
        ]);

        $this->db->query('UPDATE barang SET harga_beli_awal = harga_beli');

        $this->forge->addColumn('barang_masuk_detail', [
            'harga_beli' => [
                'type'       => 'DECIMAL',
                'constraint' => '15,2',
                'default'    => 0,
                'after'      => 'jumlah',
            ],
            'subtotal' => [
                'type'       => 'DECIMAL',
                'constraint' => '15,2',
                'default'    => 0,
                'after'      => 'harga_beli',
            ],
        ]);

        $this->db->query(
            'UPDATE barang_masuk_detail bmd
            JOIN barang b ON b.id = bmd.barang_id
            SET bmd.harga_beli = b.harga_beli_awal,
                bmd.subtotal = bmd.jumlah * b.harga_beli_awal'
        );
    }

    public function down()
    {
        $this->forge->dropColumn('barang_masuk_detail', ['harga_beli', 'subtotal']);
        $this->forge->dropColumn('barang', 'harga_beli_awal');
    }
}
