<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

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

        if (! $db->fieldExists('subtotal', 'pembelian')) {
            $this->forge->addColumn('pembelian', [
                'subtotal' => [
                    'type'       => 'BIGINT',
                    'constraint' => 20,
                    'unsigned'   => true,
                    'default'    => 0,
                    'after'      => 'nomor_dokumen',
                ],
            ]);
        }

        if (! $db->fieldExists('pajak_persen', 'pembelian')) {
            $this->forge->addColumn('pembelian', [
                'pajak_persen' => [
                    'type'       => 'INT',
                    'constraint' => 3,
                    'unsigned'   => true,
                    'default'    => 0,
                    'after'      => 'subtotal',
                ],
            ]);
        }

        if (! $db->fieldExists('pajak_nominal', 'pembelian')) {
            $this->forge->addColumn('pembelian', [
                'pajak_nominal' => [
                    'type'       => 'BIGINT',
                    'constraint' => 20,
                    'unsigned'   => true,
                    'default'    => 0,
                    'after'      => 'pajak_persen',
                ],
            ]);
        }

        if (! $db->fieldExists('total_pembelian', 'pembelian')) {
            $this->forge->addColumn('pembelian', [
                'total_pembelian' => [
                    'type'       => 'BIGINT',
                    'constraint' => 20,
                    'unsigned'   => true,
                    'default'    => 0,
                    'after'      => 'pajak_nominal',
                ],
            ]);
        }

        $db->query(
            'UPDATE pembelian p
             LEFT JOIN (
                 SELECT pembelian_id, COALESCE(SUM(subtotal), 0) AS subtotal
                 FROM pembelian_detail
                 GROUP BY pembelian_id
             ) d ON d.pembelian_id = p.id
             SET p.subtotal = COALESCE(d.subtotal, 0),
                 p.pajak_persen = COALESCE(p.pajak_persen, 0),
                 p.pajak_nominal = COALESCE(p.pajak_nominal, 0),
                 p.total_pembelian = COALESCE(NULLIF(p.total_pembelian, 0), COALESCE(d.subtotal, 0))'
        );
    }

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

        foreach (['total_pembelian', 'pajak_nominal', 'pajak_persen', 'subtotal'] as $field) {
            if ($db->fieldExists($field, 'pembelian')) {
                $this->forge->dropColumn('pembelian', $field);
            }
        }
    }
}
