<?php

declare(strict_types=1);

namespace KupShop\StoresBundle\Resources\upgrade;

class StoresLogUpgrade extends \UpgradeNew
{
    // Spustit po StoresUpgrade
    protected $priority = 100;

    protected function isAllowed(): bool
    {
        return findModule(\Modules::STOCK_IN);
    }

    public function check_storesLog()
    {
        return $this->checkTableExists('stores_log');
    }

    /** Create stores_log table */
    public function upgrade_storesLog()
    {
        sqlQuery('CREATE table stores_log(
                            id           INT AUTO_INCREMENT PRIMARY KEY,
                            time         TIMESTAMP NOT NULL DEFAULT NOW(),
                            id_product   INT       NOT NULL,
                            id_variation INT       NULL,
                            id_store     INT       NOT NULL,
                            previous       INT       NOT NULL DEFAULT 0,
                            current        INT       NOT NULL,
                            CONSTRAINT stores_id_product FOREIGN KEY (id_product) REFERENCES products (id)
                                ON DELETE CASCADE ON UPDATE CASCADE,
                            CONSTRAINT stores_id_variation FOREIGN KEY (id_variation) REFERENCES products_variations (id)
                                ON DELETE CASCADE ON UPDATE CASCADE,
                            CONSTRAINT stores_id_store FOREIGN KEY (id_store) REFERENCES stores (id)
                                ON DELETE CASCADE ON UPDATE CASCADE)');
        $this->upgradeOK();
    }

    public function check_StoresLogIdAdminField()
    {
        return $this->checkColumnExists('stores_log', 'id_admin');
    }

    /** Add id_admin field to stores_log table */
    public function upgrade_StoresLogIdAdminField()
    {
        sqlQuery('ALTER TABLE stores_log ADD COLUMN id_admin INT DEFAULT NULL');
        $this->upgradeOK();
    }

    public function check_StoresLogDataField()
    {
        return $this->checkColumnExists('stores_log', 'data');
    }

    /** Add data field to stores_log table */
    public function upgrade_StoresLogDataField()
    {
        sqlQuery('ALTER TABLE stores_log ADD COLUMN data MEDIUMTEXT DEFAULT NULL');
        $this->upgradeOK();
    }
}
