<?php

use yii\db\Migration;

/**
 * Creates invoice_items for line-item breakdown on invoices.
 */
class m240001_000006_create_invoice_items_table extends Migration
{
    public function safeUp(): void
    {
        $this->createTable('{{%invoice_items}}', [
            'id'          => $this->primaryKey()->unsigned()->comment('Primary key'),
            'invoice_id'  => $this->integer()->unsigned()->notNull()->comment('FK invoices'),
            'description' => $this->string(255)->notNull()->comment('Item description'),
            'quantity'    => $this->decimal(8, 2)->notNull()->defaultValue(1.00)->comment('Qty'),
            'unit_price'  => $this->decimal(10, 2)->notNull()->defaultValue(0.00)->comment('Price per unit'),
            'total_price' => $this->decimal(12, 2)->notNull()->defaultValue(0.00)->comment('quantity * unit_price'),
            'sort_order'  => $this->smallInteger()->unsigned()->notNull()->defaultValue(0)->comment('Display order'),
        ], 'ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT="Invoice line items"');

        $this->createIndex('idx_inv_items_invoice', '{{%invoice_items}}', 'invoice_id');

        $this->addForeignKey('fk_inv_items_invoice', '{{%invoice_items}}', 'invoice_id', '{{%invoices}}', 'id', 'CASCADE', 'CASCADE');
    }

    public function safeDown(): void
    {
        $this->dropForeignKey('fk_inv_items_invoice', '{{%invoice_items}}');
        $this->dropTable('{{%invoice_items}}');
    }
}
