<?php

namespace App\Database\Migrations;

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

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

        if ($db->tableExists('penjualan_detail') && ! $db->fieldExists('harga_beli', 'penjualan_detail')) {
            $this->forge->addColumn('penjualan_detail', [
                'harga_beli' => [
                    'type'       => 'BIGINT',
                    'constraint' => 20,
                    'unsigned'   => true,
                    'null'       => false,
                    'default'    => 0,
                    'after'      => 'harga_jual',
                ],
            ]);
        }

        if ($db->tableExists('penjualan_detail') && ! $db->fieldExists('total_modal', 'penjualan_detail')) {
            $this->forge->addColumn('penjualan_detail', [
                'total_modal' => [
                    'type'       => 'BIGINT',
                    'constraint' => 20,
                    'unsigned'   => true,
                    'null'       => false,
                    'default'    => 0,
                    'after'      => 'subtotal',
                ],
            ]);
        }

        if ($db->tableExists('penjualan_detail') && $db->tableExists('barang')) {
            $db->query(
                'UPDATE penjualan_detail pd '
                . 'LEFT JOIN barang b ON b.id = pd.barang_id '
                . 'SET pd.harga_beli = COALESCE(b.harga_beli, 0), '
                . 'pd.total_modal = pd.jumlah * COALESCE(b.harga_beli, 0) '
                . 'WHERE pd.harga_beli = 0 AND pd.total_modal = 0'
            );
        }
    }

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

        if ($db->tableExists('penjualan_detail') && $db->fieldExists('total_modal', 'penjualan_detail')) {
            $this->forge->dropColumn('penjualan_detail', 'total_modal');
        }

        if ($db->tableExists('penjualan_detail') && $db->fieldExists('harga_beli', 'penjualan_detail')) {
            $this->forge->dropColumn('penjualan_detail', 'harga_beli');
        }
    }
}
