<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * Control DB. Platform billing a hotel for their PMS subscription — the
 * mirror image of a tenant's own `folio` invoices to their guests
 * (app/Views/invoices/folio_invoice.php), but this table lives here
 * because it's platform revenue, not hotel operational data.
 */
class CreateInvoicesTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type'           => 'INT',
                'constraint'     => 11,
                'unsigned'       => true,
                'auto_increment' => true,
            ],
            'tenant_id' => [
                'type'     => 'INT',
                'constraint' => 11,
                'unsigned' => true,
            ],
            'subscription_id' => [
                'type'     => 'INT',
                'constraint' => 11,
                'unsigned' => true,
                'null'     => true,
            ],
            'invoice_number' => [
                'type'       => 'VARCHAR',
                'constraint' => 30,
                'comment'    => 'e.g. INV-2026-000123 — generated in InvoiceModel::nextInvoiceNumber(), never user-entered.',
            ],
            'amount' => [
                'type'       => 'DECIMAL',
                'constraint' => '10,2',
            ],
            'status' => [
                'type'       => 'VARCHAR',
                'constraint' => 20,
                'default'    => 'draft',
                'comment'    => 'draft|sent|paid|overdue|void — validated against Config\Lookups.',
            ],
            'due_date' => [
                'type' => 'DATE',
                'null' => true,
            ],
            'paid_at' => [
                'type' => 'DATETIME',
                'null' => true,
            ],
            'created_at' => [
                'type' => 'DATETIME',
                'null' => true,
            ],
            'updated_at' => [
                'type' => 'DATETIME',
                'null' => true,
            ],
        ]);

        $this->forge->addKey('id', true);
        $this->forge->addUniqueKey('invoice_number');
        $this->forge->addKey('tenant_id');
        $this->forge->addForeignKey('tenant_id', 'tenants', 'id', '', 'CASCADE');
        $this->forge->addForeignKey('subscription_id', 'subscriptions', 'id', '', 'SET NULL');
        $this->forge->createTable('invoices');
    }

    public function down()
    {
        $this->forge->dropTable('invoices', true);
    }
}
