<?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;

/**
 * Penalty table schema for database creation
 */
class PenaltySchema extends AbstractSchema
{
    public const TABLE_NAME = 'bflex_penalties';

    public function define(): AbstractTable
    {
        return $this->definePenaltyTable();
    }

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

        // Primary key
        $schema->column('id')->integer()->primary();

        // Penalty data
        $schema->column('amount')->bigInteger(); // Amount in minor currency units
        $schema->column('currency')->string(3); // Currency code (USD, EUR, etc.)
        $schema->column('description')->text();
        $schema->column('status')->string(50)->default('pending');

        // Dates
        $schema->column('applied_at')->datetime();

        // Payment info
        $schema->column('comment')->string();

        // Relations
        $schema->column('reservation_id')->integer();

        // Timestamps
        $this->addTimestamps($schema);

        // Indexes
        $schema->index(['status']);
        $schema->index(['reservation_id']);
        $schema->index(['applied_at']);
        $schema->index(['created_at']);

        return $schema;
    }

    public function createForeignKeys(): void
    {
        $table = $this->database->table(self::TABLE_NAME)->getSchema();

        // Foreign key to reservations table
        $table->foreignKey(['reservation_id'])
            ->references(ReservationSchema::TABLE_NAME, ['id'])
            ->onDelete('CASCADE'); // Delete penalties when reservation is deleted

        $table->save();
    }
}
