<?php

namespace Tenant\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * `unit_price` is captured at order time (not looked up live from
 * menu_items) so a later menu price change never rewrites an already-
 * placed order's total. `kitchen_status` is per-item, not per-order —
 * the kitchen display lets staff mark individual items ready.
 */
class CreatePosOrderItemsTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type'           => 'INT',
                'constraint'     => 11,
                'unsigned'       => true,
                'auto_increment' => true,
            ],
            'pos_order_id' => [
                'type'     => 'INT',
                'constraint' => 11,
                'unsigned' => true,
            ],
            'menu_item_id' => [
                'type'     => 'INT',
                'constraint' => 11,
                'unsigned' => true,
            ],
            'item_name' => [
                'type'       => 'VARCHAR',
                'constraint' => 150,
                'comment'    => 'Snapshot of menu_items.name at order time',
            ],
            'quantity' => [
                'type'       => 'INT',
                'constraint' => 5,
                'unsigned'   => true,
                'default'    => 1,
            ],
            'unit_price' => [
                'type'       => 'DECIMAL',
                'constraint' => '10,2',
            ],
            'kitchen_status' => [
                'type'       => 'VARCHAR',
                'constraint' => 20,
                'default'    => 'pending',
                'comment'    => 'pending, ready',
            ],
            'created_at' => ['type' => 'DATETIME', 'null' => true],
            'updated_at' => ['type' => 'DATETIME', 'null' => true],
        ]);

        $this->forge->addKey('id', true);
        $this->forge->addKey('pos_order_id');
        $this->forge->addForeignKey('pos_order_id', 'pos_orders', 'id', '', 'CASCADE');
        $this->forge->addForeignKey('menu_item_id', 'menu_items', 'id', '', 'RESTRICT');
        $this->forge->createTable('pos_order_items');
    }

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