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

declare(strict_types=1);

namespace BookiFlex\Extensions\Cart\ORM\Schema;

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

defined( 'ABSPATH' ) || exit;

/**
 * Cart table schema
 */
class CartSchema extends AbstractSchema
{
    public const TABLE_NAME = 'bflex_carts';

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

    protected function defineCartTable(): AbstractTable
    {
        $schema = $this->database->table(self::TABLE_NAME)->getSchema();
        $schema->column('id')->integer()->primary();
        $schema->column('session_id')->string(255);
        $schema->column('currency')->string(3)->default('USD');
        $schema->column('status')->string(50)->default('pending');
        $schema->column('promo_code')->string()->nullable();
        $schema->column('special_request')->text()->nullable();
        $schema->column('arrival_time')->string(5)->nullable();
        $schema->column('check_in_time')->string(5);
        $schema->column('check_out_time')->string(5);
        $schema->column('customer_id')->integer()->nullable();
        $this->addTimestamps($schema);

        // Indexes
        $schema->index(['session_id'])->unique();
        $schema->index(['status']);
        $schema->index(['created_at']);
        $schema->index(['updated_at']);

        return $schema;
    }

    public function createForeignKeys(): void
    {
        $table = $this->database->table(self::TABLE_NAME)->getSchema();
        $table->foreignKey(['customer_id'])
            ->references(CustomerSchema::TABLE_NAME, ['id'])
            ->onDelete('SET NULL');
        $table->save();
    }
}
