<?php

use yii\db\Migration;

/**
 * Creates payments table for tracking partial and full payments against invoices.
 */
class m240001_000007_create_payments_table extends Migration
{
    public function safeUp(): void
    {
        $this->createTable('{{%payments}}', [
            'id'             => $this->primaryKey()->unsigned()->comment('Primary key'),
            'invoice_id'     => $this->integer()->unsigned()->notNull()->comment('FK invoices'),
            'customer_id'    => $this->integer()->unsigned()->notNull()->comment('FK customers (denormalized for fast queries)'),
            'amount'         => $this->decimal(12, 2)->notNull()->comment('Amount paid in this transaction'),
            'payment_method' => "ENUM('cash','upi','card','bank_transfer','cheque','other') NOT NULL DEFAULT 'cash' COMMENT 'Payment method'",
            'payment_date'   => $this->date()->notNull()->comment('Date payment was made'),
            'reference_no'   => $this->string(100)->null()->comment('Transaction ID / cheque number'),
            'notes'          => $this->text()->null()->comment('Internal notes'),
            'created_by'     => $this->integer()->unsigned()->null()->comment('Admin user ID'),
            'created_at'     => $this->integer()->unsigned()->notNull()->comment('Unix timestamp'),
        ], 'ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT="Payment records (supports partial payments)"');

        $this->createIndex('idx_pay_invoice', '{{%payments}}', 'invoice_id');
        $this->createIndex('idx_pay_customer', '{{%payments}}', 'customer_id');
        $this->createIndex('idx_pay_date', '{{%payments}}', 'payment_date');

        $this->addForeignKey('fk_pay_invoice', '{{%payments}}', 'invoice_id', '{{%invoices}}', 'id', 'CASCADE', 'CASCADE');
        $this->addForeignKey('fk_pay_customer', '{{%payments}}', 'customer_id', '{{%customers}}', 'id', 'CASCADE', 'CASCADE');
    }

    public function safeDown(): void
    {
        $this->dropForeignKey('fk_pay_invoice', '{{%payments}}');
        $this->dropForeignKey('fk_pay_customer', '{{%payments}}');
        $this->dropTable('{{%payments}}');
    }
}
