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

declare(strict_types=1);

namespace BookiFlex\Extensions\Payment\ORM\Schema;

use BookiFlex\Core\ORM\Schema\AbstractSchema;
use BookiFlex\Core\ORM\Schema\ReservationSchema;
use Cycle\Database\Schema\AbstractTable;

defined( 'ABSPATH' ) || exit;

/**
 * Payment allocation table schema
 */
class PaymentAllocationSchema extends AbstractSchema
{
    public const TABLE_NAME        = 'bflex_payment_allocations';

    public function define(): AbstractTable
    {
        $schema = $this->database->table(self::TABLE_NAME)->getSchema();
        $schema->column('id')->integer()->primary();
        $schema->column('type')->string(20);
        $schema->column('payment_id')->integer();
        $schema->column('reservation_id')->integer();
        $schema->column('amount')->integer();
        $schema->column('currency')->string(3)->nullable()->defaultValue(null);
        $this->addTimestamps($schema);

        // Indexes
        $schema->index(['payment_id']);
        $schema->index(['reservation_id']);

        return $schema;
    }

    public function createForeignKeys(): void
    {
        /** @var AbstractTable $table */
        $table = $this->database->table(self::TABLE_NAME)->getSchema();
        $table->foreignKey(['payment_id'])
            ->references(PaymentSchema::TABLE_NAME)
            ->onDelete('CASCADE');

        $table->foreignKey(['reservation_id'])
            ->references(ReservationSchema::TABLE_NAME)
            ->onDelete('CASCADE');
        $table->save();
    }
}
