<?php
/**
 * BookiFlex Core
 *
 * @package    BookiFlex
 * @subpackage Core
 * @author     BookiFlex
 * @copyright  Copyright (c) 2025 BookiFlex
 * @license    GPL-2.0-or-later
 *
 * @link       https://bookiflex.com
 */

declare(strict_types=1);

namespace BookiFlex\Core\ORM\Schema;

use Cycle\Database\Schema\AbstractTable;

defined( 'ABSPATH' ) || exit;

/**
 * Reservation tables schema
 */
class ReservationSchema extends AbstractSchema
{
    public const TABLE_NAME = 'bflex_reservations';

    public function define(): AbstractTable
    {
        // This returns the main reservation table
        // Other tables are created via additional methods
        return $this->defineReservationTable();
    }

    protected function defineReservationTable(): AbstractTable
    {
        $schema = $this->database->table(self::TABLE_NAME)->getSchema();

        $schema->column('id')->integer()->primary();
        $schema->column('sid')->string(36);
        $schema->column('status')->string(25);
        $schema->column('currency')->string(3);
        $schema->column('language')->string(5);
        $schema->column('check_in_date')->date();
        $schema->column('check_out_date')->date();
        $schema->column('check_in_time')->time();
        $schema->column('check_out_time')->time();
        $schema->column('origin_source_code')->string(25);
        $schema->column('number')->string(25)->defaultValue('');
        $schema->column('special_request')->text()->nullable();
        $schema->column('cancellation_code')->string(10)->defaultValue('');
        $schema->column('group_id')->integer()->nullable();
        $schema->column('customer_id')->integer()->nullable();
        $schema->column('cancellation_policy_id')->bigInteger()->nullable();
        $schema->column('payment_type_id')->bigInteger()->nullable();
        $schema->column('total_amount')->integer()->nullable();
        $schema->column('waiting_payment_until')->datetime()->nullable();
        $schema->column('cancelled_by')->string(10)->nullable();
        $schema->column('cancelled_at')->datetime()->nullable();
        $schema->column('cancellation_reason')->text()->nullable();

        $this->addTimestamps($schema);

        // Indexes
        $schema->index(['sid'])->unique();
        $schema->index(['customer_id']);
        $schema->index(['status']);
        $schema->index(['check_in_date']);
        $schema->index(['check_out_date']);
        $schema->index(['check_in_date', 'check_out_date']);

        return $schema;
    }

    public function createForeignKeys(): void
    {
        // Foreign key to reservation groups
        $table = $this->database->table(self::TABLE_NAME)->getSchema();
        $table->foreignKey(['group_id'])
            ->references(ReservationGroupSchema::TABLE_NAME, ['id'])
            ->onDelete('SET NULL');
        $table->save();
    }
}
