<?php

use yii\db\Migration;

/**
 * Links customers to plans with subscription tracking.
 */
class m240001_000004_create_customer_plans_table extends Migration
{
    public function safeUp(): void
    {
        $this->createTable('{{%customer_plans}}', [
            'id'          => $this->primaryKey()->unsigned()->comment('Primary key'),
            'customer_id' => $this->integer()->unsigned()->notNull()->comment('FK customers'),
            'plan_id'     => $this->integer()->unsigned()->notNull()->comment('FK plans'),
            'start_date'  => $this->date()->notNull()->comment('Plan start date'),
            'end_date'    => $this->date()->null()->comment('Plan end date; NULL for one-time'),
            'status'      => "ENUM('active','expired','cancelled') NOT NULL DEFAULT 'active' COMMENT 'Subscription status'",
            'created_at'  => $this->integer()->unsigned()->notNull()->comment('Unix timestamp'),
            'updated_at'  => $this->integer()->unsigned()->notNull()->comment('Unix timestamp'),
        ], 'ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT="Customer plan subscriptions"');

        $this->createIndex('idx_cp_customer', '{{%customer_plans}}', 'customer_id');
        $this->createIndex('idx_cp_plan', '{{%customer_plans}}', 'plan_id');
        $this->createIndex('idx_cp_status', '{{%customer_plans}}', 'status');
        $this->createIndex('idx_cp_end_date', '{{%customer_plans}}', 'end_date');

        $this->addForeignKey('fk_cp_customer', '{{%customer_plans}}', 'customer_id', '{{%customers}}', 'id', 'CASCADE', 'CASCADE');
        $this->addForeignKey('fk_cp_plan', '{{%customer_plans}}', 'plan_id', '{{%plans}}', 'id', 'CASCADE', 'CASCADE');
    }

    public function safeDown(): void
    {
        $this->dropForeignKey('fk_cp_customer', '{{%customer_plans}}');
        $this->dropForeignKey('fk_cp_plan', '{{%customer_plans}}');
        $this->dropTable('{{%customer_plans}}');
    }
}
