<?php

namespace Tenant\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * `folio_id` is set only once the order is settled (see PosOrderModel::
 * settleDirect()/settleToRoom()) — it points at whichever folio actually
 * received the charge: a fresh standalone folio for a direct-pay order,
 * or the guest's existing open room folio for charge-to-room. Nullable
 * because an order sitting at open/sent_to_kitchen/served hasn't been
 * settled yet and has no folio relationship at all.
 */
class CreatePosOrdersTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type'           => 'INT',
                'constraint'     => 11,
                'unsigned'       => true,
                'auto_increment' => true,
            ],
            'order_type' => [
                'type'       => 'VARCHAR',
                'constraint' => 20,
                'comment'    => 'dine_in, takeaway',
            ],
            'dining_table_id' => [
                'type'     => 'INT',
                'constraint' => 11,
                'unsigned' => true,
                'null'     => true,
            ],
            'guest_id' => [
                'type'     => 'INT',
                'constraint' => 11,
                'unsigned' => true,
                'null'     => true,
            ],
            'status' => [
                'type'       => 'VARCHAR',
                'constraint' => 20,
                'default'    => 'open',
                'comment'    => 'open, sent_to_kitchen, served, paid',
            ],
            'folio_id' => [
                'type'     => 'INT',
                'constraint' => 11,
                'unsigned' => true,
                'null'     => true,
            ],
            'opened_by' => [
                'type'     => 'INT',
                'constraint' => 11,
                'unsigned' => true,
                'null'     => true,
            ],
            'created_at' => ['type' => 'DATETIME', 'null' => true],
            'updated_at' => ['type' => 'DATETIME', 'null' => true],
        ]);

        $this->forge->addKey('id', true);
        $this->forge->addKey('status');
        $this->forge->addKey('dining_table_id');
        $this->forge->addKey('guest_id');
        $this->forge->addForeignKey('dining_table_id', 'dining_tables', 'id', '', 'SET NULL');
        $this->forge->addForeignKey('guest_id', 'guests', 'id', '', 'SET NULL');
        $this->forge->addForeignKey('folio_id', 'folios', 'id', '', 'SET NULL');
        $this->forge->addForeignKey('opened_by', 'users', 'id', '', 'SET NULL');
        $this->forge->createTable('pos_orders');
    }

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