<?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 Cycle\Database\Schema\AbstractTable;

defined( 'ABSPATH' ) || exit;

/**
 * Cart items table schema
 */
class CartItemSchema extends AbstractSchema
{
    public const TABLE_NAME = 'bflex_cart_items';

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

    protected function defineCartItemTable(): AbstractTable
    {
        $schema = $this->database->table(self::TABLE_NAME)->getSchema();
        $schema->column('id')->integer()->primary();
        $schema->column('cart_id')->integer();
        $schema->column('type')->string(50);
        $schema->column('hash')->string(64);
        $schema->column('quantity')->integer()->default(1);
        $schema->column('unit_price')->decimal(10, 2)->nullable();
        $schema->column('summary')->json();
        $schema->column('data')->json();
        $schema->column('sort_order')->integer()->nullable();
        $this->addTimestamps($schema);

        // Indexes
        $schema->index(['cart_id']);
        $schema->index(['type']);
        $schema->index(['hash']);
        $schema->index(['cart_id', 'hash'])->unique();

        return $schema;
    }

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