<?php

use yii\db\Migration;

/**
 * Migration for Surf Invoices Module
 * 
 * Creates invoices and credit_notes tables
 * Adds invoice linkage columns to basket table
 */
class m260311_000001_create_invoicing_tables extends Migration
{
    /**
     * {@inheritdoc}
     */
    public function safeUp()
    {
        // Add columns to basket table for invoice linkage
        $this->addColumn('basket', 'invoiceid', $this->integer()->comment('Link to generated invoice'));
        $this->addColumn('basket', 'invoiced_by', $this->string(255)->comment('User/system that triggered invoice generation'));
        $this->addColumn('basket', 'invoicedate', $this->integer()->comment('Timestamp when invoice was generated'));

        // Create invoices table
        $this->createTable('invoices', [
            'id' => $this->primaryKey(),
            
            // Linkage and idempotency
            'source_cart_id' => $this->integer()->notNull()->comment('Source cart ID'),
            'source_centrearrddate' => $this->datetime()->comment('Center arrival date from source cart'),
            'generated_at' => $this->datetime()->notNull()->comment('When invoice was generated'),
            'generation_key' => $this->string(255)->unique()->notNull()->comment('Unique key for idempotency'),
            
            // Invoice metadata
            'invoice_number' => $this->string(100)->notNull()->unique()->comment('Invoice number for reference'),
            
            // Snapshot from cart - immutable
            'cartid' => $this->string(255)->comment('Original cart ID'),
            'email' => $this->string(255)->comment('Customer email'),
            'name' => $this->string(255)->comment('Customer name'),
            'namefirstname' => $this->string(255)->comment('Customer first name'),
            'namelastname' => $this->string(255)->comment('Customer last name'),
            'telephone' => $this->string(20)->comment('Customer phone'),
            'fulladdress' => $this->text()->comment('Customer address'),
            'postcode' => $this->string(20)->comment('Postcode'),
            'centername' => $this->string(255)->comment('Center name'),
            'centrearrddate' => $this->datetime()->comment('Center arrival date'),
            'centredepdate' => $this->datetime()->comment('Center departure date'),
            
            // Financial snapshot
            'subtotal' => $this->decimal(19, 2)->defaultValue(0)->comment('Invoice subtotal'),
            'total' => $this->decimal(19, 2)->defaultValue(0)->comment('Invoice total'),
            'tax' => $this->decimal(19, 2)->defaultValue(0)->comment('Tax amount'),
            'shipping' => $this->decimal(19, 2)->defaultValue(0)->comment('Shipping cost'),
            'amountpaid' => $this->decimal(19, 2)->defaultValue(0)->comment('Amount paid'),
            
            // Order metadata
            'ordernumber' => $this->string(100)->comment('Order number'),
            'orderref' => $this->string(100)->comment('Order reference'),
            'status' => $this->string(50)->comment('Order status'),
            'billingstatus' => $this->string(50)->comment('Billing status'),
            'paymentmethod' => $this->string(50)->comment('Payment method'),
            
            // Audit snapshot
            'source_snapshot_json' => $this->mediumText()->comment('Complete JSON snapshot of source cart at generation time'),
        ]);

        // Indexes for invoices table
        $this->createIndex('idx_invoices_source_cart_id', 'invoices', 'source_cart_id');
        $this->createIndex('idx_invoices_generation_key', 'invoices', 'generation_key');
        $this->createIndex('idx_invoices_invoice_number', 'invoices', 'invoice_number');
        $this->createIndex('idx_invoices_generated_at', 'invoices', 'generated_at');

        // Foreign keys (credit_notes table created by portalpeople/credit-notes package)
        $this->addForeignKey(
            'fk_invoices_source_cart_id',
            'invoices',
            'source_cart_id',
            'basket',
            'id',
            'RESTRICT',
            'RESTRICT'
        );

        $this->addForeignKey(
            'fk_basket_invoiceid',
            'basket',
            'invoiceid',
            'invoices',
            'id',
            'SET NULL',
            'CASCADE'
        );
    }

    /**
     * {@inheritdoc}
     */
    public function safeDown()
    {
        // Drop foreign keys
        $this->dropForeignKey('fk_invoices_source_cart_id', 'invoices');
        $this->dropForeignKey('fk_basket_invoiceid', 'basket');

        // Drop invoice table
        $this->dropTable('invoices');

        // Drop columns from basket
        $this->dropColumn('basket', 'invoiceid');
        $this->dropColumn('basket', 'invoiced_by');
        $this->dropColumn('basket', 'invoicedate');
    }
}
