<?php

namespace Tenant\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * `booking_id` is nullable and `guest_id` is carried directly on the folio
 * (not derived only through the booking) — Phase 1 always sets both, but
 * Phase 2 needs standalone folios for walk-in restaurant guests and event
 * clients who never have a booking_id, and this shape means that's just a
 * new folio row, not a schema change.
 *
 * `status` (open/closed) isn't named in the Phase 1 spec explicitly; added
 * so checkout can mark a folio settled. Flagged as an assumption.
 */
class CreateFoliosTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type'           => 'INT',
                'constraint'     => 11,
                'unsigned'       => true,
                'auto_increment' => true,
            ],
            'booking_id' => [
                'type'     => 'INT',
                'constraint' => 11,
                'unsigned' => true,
                'null'     => true,
            ],
            'guest_id' => [
                'type'     => 'INT',
                'constraint' => 11,
                'unsigned' => true,
            ],
            'status' => [
                'type'       => 'VARCHAR',
                'constraint' => 20,
                'default'    => 'open',
                'comment'    => 'open, closed',
            ],
            'opened_at' => [
                'type' => 'DATETIME',
            ],
            'closed_at' => [
                'type' => 'DATETIME',
                'null' => true,
            ],
            'created_at' => ['type' => 'DATETIME', 'null' => true],
            'updated_at' => ['type' => 'DATETIME', 'null' => true],
        ]);

        $this->forge->addKey('id', true);
        $this->forge->addKey('booking_id');
        $this->forge->addKey('guest_id');
        $this->forge->addKey('status');
        $this->forge->addForeignKey('booking_id', 'bookings', 'id', '', 'SET NULL');
        $this->forge->addForeignKey('guest_id', 'guests', 'id', '', 'RESTRICT');
        $this->forge->createTable('folios');
    }

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