<?php

namespace Tenant\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * `status` and `source` are VARCHAR, driven by App\Config\BookingStatus /
 * App\Config\BookingSource rather than a DB ENUM or a literal dropdown in
 * a view — Phase 3 adds a `pending_deposit` status, which then only needs
 * a one-line addition to the config array, not a migration.
 */
class CreateBookingsTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type'           => 'INT',
                'constraint'     => 11,
                'unsigned'       => true,
                'auto_increment' => true,
            ],
            'guest_id' => [
                'type'     => 'INT',
                'constraint' => 11,
                'unsigned' => true,
            ],
            'room_id' => [
                'type'     => 'INT',
                'constraint' => 11,
                'unsigned' => true,
            ],
            'check_in_date' => [
                'type' => 'DATE',
            ],
            'check_out_date' => [
                'type' => 'DATE',
            ],
            'status' => [
                'type'       => 'VARCHAR',
                'constraint' => 20,
                'default'    => 'confirmed',
            ],
            'source' => [
                'type'       => 'VARCHAR',
                'constraint' => 20,
                'default'    => 'walk_in',
            ],
            'rate_applied' => [
                'type'       => 'DECIMAL',
                'constraint' => '10,2',
                'null'       => true,
            ],
            'notes' => [
                'type' => 'TEXT',
                'null' => true,
            ],
            'created_at' => ['type' => 'DATETIME', 'null' => true],
            'updated_at' => ['type' => 'DATETIME', 'null' => true],
        ]);

        $this->forge->addKey('id', true);
        $this->forge->addKey('guest_id');
        $this->forge->addKey(['room_id', 'check_in_date', 'check_out_date'], false, false, 'idx_room_dates');
        $this->forge->addKey('status');
        $this->forge->addForeignKey('guest_id', 'guests', 'id', '', 'RESTRICT');
        $this->forge->addForeignKey('room_id', 'rooms', 'id', '', 'RESTRICT');
        $this->forge->createTable('bookings');
    }

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