<?php

namespace KupShop\DynamicRelatedProductsBundle\Resources\upgrade;

class DynamicRelatedProductsUpgrade extends \UpgradeNew
{
    public function check_ProductsRelatedDynamicTable(): bool
    {
        return $this->checkTableExists('products_related_dynamic');
    }

    /** [2023-09-26] Create dynamic products related table */
    public function upgrade_ProductsRelatedDynamicTable(): void
    {
        sqlQuery('
            CREATE TABLE products_related_dynamic (
                id                          INT AUTO_INCREMENT,
                id_products_related_types   INT                                     NOT NULL,
                name                        VARCHAR(100)                            NOT NULL,
                data                        LONGTEXT                                NOT NULL,
                created_at                  DATETIME DEFAULT CURRENT_TIMESTAMP()    NULL,
                updated_at                  DATETIME                                NULL,
                CONSTRAINT products_related_dynamic_pk PRIMARY KEY (id)
            );
        ');

        $this->upgradeOK();
    }

    public function check_AddColumnToProductsRelated(): bool
    {
        return $this->checkColumnExists('products_related', 'id_products_related_dynamic');
    }

    /** [2023-09-26] Added id_products_related_dynamic column to products_related table */
    public function upgrade_AddColumnToProductsRelated(): void
    {
        sqlQuery('
            ALTER TABLE products_related
            ADD id_products_related_dynamic INT NULL,
            ADD CONSTRAINT products_related_products_related_dynamic_id_fk
                FOREIGN KEY (id_products_related_dynamic) REFERENCES products_related_dynamic (id)
                ON UPDATE CASCADE ON DELETE CASCADE;
        ');

        $this->upgradeOK();
    }

    public function check_AddForeignKey(): bool
    {
        return findModule(\Modules::PRODUCTS_RELATED, \Modules::SUB_TYPES) && $this->checkForeignKeyExists('products_related_dynamic', 'id_products_related_types');
    }

    /** [2023-10-17] Added foreign key for products_related_types */
    public function upgrade_AddForeignKey(): void
    {
        sqlQuery('
            ALTER TABLE products_related_dynamic
            ADD CONSTRAINT products_related_dynamic_products_related_types_id_fk
                FOREIGN KEY (id_products_related_types) REFERENCES products_related_types (id)
                ON UPDATE CASCADE ON DELETE CASCADE;
        ');

        $this->upgradeOK();
    }
}
