<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;
use Config\Database;

class RequirePenjualanDetailCostSnapshot extends Migration
{
    public function up()
    {
        $db = Database::connect();

        if (! $db->tableExists('penjualan_detail')) {
            return;
        }

        $db->table('penjualan_detail')
            ->set('harga_beli', 'COALESCE(harga_beli, 0)', false)
            ->set('total_modal', 'COALESCE(total_modal, jumlah * COALESCE(harga_beli, 0))', false)
            ->update();

        if ($db->fieldExists('harga_beli', 'penjualan_detail')) {
            $this->forge->modifyColumn('penjualan_detail', [
                'harga_beli' => [
                    'name'       => 'harga_beli',
                    'type'       => 'BIGINT',
                    'constraint' => 20,
                    'unsigned'   => true,
                    'null'       => false,
                    'default'    => 0,
                ],
            ]);
        }

        if ($db->fieldExists('total_modal', 'penjualan_detail')) {
            $this->forge->modifyColumn('penjualan_detail', [
                'total_modal' => [
                    'name'       => 'total_modal',
                    'type'       => 'BIGINT',
                    'constraint' => 20,
                    'unsigned'   => true,
                    'null'       => false,
                    'default'    => 0,
                ],
            ]);
        }
    }

    public function down()
    {
        $db = Database::connect();

        if (! $db->tableExists('penjualan_detail')) {
            return;
        }

        if ($db->fieldExists('harga_beli', 'penjualan_detail')) {
            $this->forge->modifyColumn('penjualan_detail', [
                'harga_beli' => [
                    'name'       => 'harga_beli',
                    'type'       => 'BIGINT',
                    'constraint' => 20,
                    'unsigned'   => true,
                    'null'       => true,
                    'default'    => 0,
                ],
            ]);
        }

        if ($db->fieldExists('total_modal', 'penjualan_detail')) {
            $this->forge->modifyColumn('penjualan_detail', [
                'total_modal' => [
                    'name'       => 'total_modal',
                    'type'       => 'BIGINT',
                    'constraint' => 20,
                    'unsigned'   => true,
                    'null'       => true,
                    'default'    => 0,
                ],
            ]);
        }
    }
}
