<?php

class Upgrade35 extends UpgradeNew
{
    public function checkRightfulness_1()
    {
        return isDevelopment() && findModule('eshop_users') && !defined('TEST_SUITE')
            && returnSQLResult('SELECT id FROM users WHERE email=:email', ['email' => 'wpj@wpj.cz']) == false;
    }

    /** Development - make sure wpj@wpj.cz user exists */
    public function makeChanges_1()
    {
        sqlQuery(
            'INSERT IGNORE INTO users (email, passw, `name`, surname)
              VALUES (:email, :passwd, :name, :surname)
              ON DUPLICATE KEY UPDATE email=VALUES(email), passw=VALUES(passw), `name`=VALUES(`name`), surname=VALUES(surname)',
            [
                'email' => 'wpj@wpj.cz',
                'passwd' => password_hash('wpj', PASSWORD_DEFAULT),
                'name' => 'Wpj',
                'surname' => 'Wpj',
            ]
        );

        $this->upgradeOK();
    }

    public function checkRightfulness_2()
    {
        return findModule('abra') && $this->checkTableExists('abra_producers');
    }

    /** Abra sync - add abra producers sync tables */
    public function makeChanges_2()
    {
        sqlQuery('CREATE TABLE abra_producers (
         `id_abra` VARCHAR(30) NOT NULL,
         `id_producer` INT UNSIGNED NOT NULL
      ) ENGINE=InnoDB');

        sqlQuery('ALTER TABLE `abra_producers`
        ADD KEY `id_abra` (`id_abra`)');

        sqlQuery('ALTER TABLE `abra_producers`
        ADD CONSTRAINT `abra_producers_ibfk_1` FOREIGN KEY (`id_producer`) REFERENCES `producers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE');

        $this->upgradeOK();
    }

    public function checkRightfulness_3()
    {
        return findModule('products_variations') && $this->checkColumnIsNull('products_variations', 'in_store', false);
    }

    /** Product Variations - make in_store not null */
    public function makeChanges_3()
    {
        sqlQuery("ALTER TABLE `products_variations` CHANGE `in_store` `in_store` INT(10) NOT NULL DEFAULT '0'");

        $this->upgradeOK();
    }

    public function checkRightfulness_4()
    {
        return findModule('products_sections') && $this->checkColumnExists('sections', 'name_short');
    }

    /** Add sections.name_short column */
    public function makeChanges_4()
    {
        sqlQuery('ALTER TABLE `sections` ADD COLUMN `name_short` VARCHAR(50) DEFAULT NULL AFTER name');

        $this->upgradeOK();
    }

    public function checkRightfulness_5()
    {
        return findModule('order_payment') && $this->checkColumnType('order_payments', 'payment_data', 'TEXT');
    }

    /** Order_payments - change type INT to TEXT */
    public function makeChanges_5()
    {
        sqlQuery('ALTER TABLE order_payments CHANGE payment_data payment_data TEXT');

        $this->upgradeOK();
    }

    public function checkRightfulness_6()
    {
        return findModule('products_variations') && $this->checkColumnExists('sections', 'list_variations');
    }

    /** Add section.list_variations column */
    public function makeChanges_6()
    {
        sqlQuery("ALTER TABLE sections ADD COLUMN list_variations ENUM('Y','N') NOT NULL DEFAULT 'N' AFTER `date`");

        $this->upgradeOK();
    }

    public function check_makeZIPLarger()
    {
        return findModule('eshop_users') && $this->checkColumnType('users', 'zip', 'VARCHAR(50)');
    }

    /** Make ZIP fields 50 chars long */
    public function upgrade_makeZIPLarger()
    {
        sqlQuery("ALTER TABLE `users` CHANGE `delivery_zip` `delivery_zip` VARCHAR( 50 ) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT ''");
        sqlQuery("ALTER TABLE `users` CHANGE `zip` `zip` VARCHAR( 50 ) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT ''");

        $this->upgradeOK();
    }

    public function check_kindOfPhotos()
    {
        global $cfg;
        if (!isset($cfg['Photo']['kind'])) {
            return false;
        }

        return $this->checkColumnType('photos_products_relation', 'show_in_lead', "enum('".join("','", array_keys($cfg['Photo']['kind']))."')");
    }

    /** Dynamic change enum of photos_products_relation */
    public function upgrade_kindOfPhotos()
    {
        global $cfg;

        sqlQuery("ALTER TABLE photos_products_relation CHANGE show_in_lead show_in_lead ENUM('".join("','", array_keys($cfg['Photo']['kind']))."') NOT NULL DEFAULT 'N'");

        $this->upgradeOK();
    }

    public function check_variationFigure()
    {
        return $this->checkColumnExists('products_variations', 'figure');
    }

    /** Products Variation - add figure field to hide variations */
    public function upgrade_variationFigure()
    {
        sqlQuery("ALTER TABLE products_variations ADD figure ENUM('Y','N') NOT NULL DEFAULT 'Y'");

        sqlQuery('UPDATE products_variations SET figure="Y"');

        $this->upgradeOK();
    }

    public function check_API()
    {
        return findModule('eshop_users') && findModule('api') && $this->checkColumnExists('users', 'api');
    }

    /** API - add api fields into users */
    public function upgrade_API()
    {
        sqlQuery("ALTER TABLE users ADD api ENUM('Y','N') NOT NULL DEFAULT 'N'");
        sqlQuery('ALTER TABLE users ADD api_password VARCHAR(60) DEFAULT NULL');

        $this->upgradeOK();
    }

    public function check_SectionsFlags()
    {
        return $this->checkColumnExists('sections', 'flags');
    }

    /** Add flags column into sections */
    public function upgrade_SectionsFlags()
    {
        sqlQuery('ALTER TABLE sections ADD COLUMN `flags` SET(\'\') NOT NULL');

        $this->upgradeOK();
    }

    // overi, jestli je opravnene provest upgrade
    public function check_SectionsFlagsUpdate()
    {
        global $cfg;

        if (isset($cfg['Sections']['Flags'])) {
            $type = '';
            $this->checkEnumExists('sections', 'flags', 'bžet', $type);

            foreach ($cfg['Sections']['Flags'] as $name => $flag) {
                if (strstr($type, "'{$name}'") === false) {
                    return true;
                }
            }
        }

        return false;
    }

    /** Update sections flags */
    public function upgrade_SectionsFlagsUpdate()
    {
        global $cfg;

        $type = '';
        $this->checkEnumExists('sections', 'flags', 'bžet', $type);

        foreach ($cfg['Sections']['Flags'] as $name => $flag) {
            if (strstr($type, "'{$name}'") === false) {
                $type = str_replace(')', ",'{$name}')", $type);
            }
        }

        sqlQuery("ALTER TABLE sections CHANGE `flags` `flags` {$type} NOT NULL");

        $this->upgradeOK();
    }

    public function check_watchdog_last_in_store()
    {
        return findModule('watchdog') && $this->checkColumnExists('products_watchdog', 'last_in_store');
    }

    public function upgrade_watchdog_last_in_store()
    {
        sqlQuery('ALTER TABLE products_watchdog ADD COLUMN `last_in_store` INT');
        $this->upgradeOK();
    }

    //    public function check_ModuleSectionsLead()
    //    {
    //        $count = returnSQLResult("SELECT COUNT(*) FROM sections WHERE lead_figure='Y'");
    //
    //        return !findModule('sections_lead') && $count;
    //    }
    //
    //    /** Check if modul sections_lead is added */
    //    public function upgrade_ModuleSectionsLead()
    //    {
    //        die('<h2>Chybi v configu modul: $cfg[\'Modules\'][\'sections_lead\'] = true;</h2>');
    //    }

    public function check_IncreaseAdminLogin()
    {
        return $this->checkColumnType('admins', 'login', 'VARCHAR(50)');
    }

    /** Change `login` from varchar(20) to varchar(50) */
    public function upgrade_IncreaseAdminLogin()
    {
        sqlQuery("ALTER TABLE admins CHANGE COLUMN `login` `login` VARCHAR(50) NOT NULL DEFAULT ''");

        $this->upgradeOK();
    }

    public function check_AddSectionsSeznamFeed()
    {
        return $this->checkColumnExists('sections', 'feed_seznam');
    }

    /** Add feed_seznam field to sections */
    public function upgrade_AddSectionsSeznamFeed()
    {
        /*
         CREATE TABLE kupshop_shared.feed_seznam (
            `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
            `name` varchar(100) COLLATE utf8mb4_general_ci NOT NULL,
            `category_text` varchar(250) COLLATE utf8mb4_general_ci NOT NULL
          )
       */
        sqlQuery('ALTER TABLE sections ADD COLUMN `feed_seznam` INT(11) DEFAULT NULL');

        $this->upgradeOK();
    }

    public function check_watchdog_supports_variations()
    {
        return findmodule('watchdog') && $this->checkColumnExists('products_watchdog', 'id_variation');
    }

    /** Add `id_variation` column to `products_watchdog` table */
    public function upgrade_watchdog_supports_variations()
    {
        sqlQuery('ALTER TABLE products_watchdog ADD COLUMN id_variation INT DEFAULT NULL AFTER id_product');
        sqlQuery('ALTER TABLE products_watchdog ADD CONSTRAINT FOREIGN KEY (id_variation) REFERENCES products_variations(id) ON DELETE CASCADE ON UPDATE CASCADE');
        $this->upgradeOK();
    }

    public function check_ProductsInArticles()
    {
        return findmodule(\Modules::ARTICLES) && $this->checkTableExists('products_in_articles');
    }

    /** Add products to articles */
    public function upgrade_ProductsInArticles()
    {
        sqlQuery('CREATE TABLE products_in_articles (
         `id_product` INT(11),
         `id_article` INT(11)
      ) ENGINE=InnoDB;

      ALTER TABLE products_in_articles ADD CONSTRAINT `abra_products_in_articles_ibfk_1` FOREIGN KEY (id_product) REFERENCES products(id) ON DELETE CASCADE ON UPDATE CASCADE;
      ALTER TABLE products_in_articles ADD CONSTRAINT `abra_products_in_articles_ibfk_2` FOREIGN KEY (id_article) REFERENCES articles(id) ON DELETE CASCADE ON UPDATE CASCADE;
      ');

        $this->upgradeOK();
    }

    public function check_Reviews()
    {
        return findmodule('reviews') && $this->checkTableExists('reviews');
    }

    /** Add reviews */
    public function upgrade_Reviews()
    {
        sqlQuery('CREATE TABLE reviews (
        `id` INT(11) UNSIGNED NOT NULL,
        `id_product` INT(11) NOT NULL,
        `id_product_variation` INT(11) NOT NULL,
        `date` DATETIME NOT NULL,
        `rating` FLOAT(2,1),
        `recommends` TINYINT(1),
        `pros` TEXT,
        `cons` TEXT,
        `summary` TEXT,
        `name` VARCHAR(30),
        PRIMARY KEY (id),
        CONSTRAINT `reviews_products_fk` FOREIGN KEY (id_product) REFERENCES products(id) ON DELETE CASCADE ON UPDATE CASCADE,
        CONSTRAINT `reviews_products_variations_fk` FOREIGN KEY (id_product_variation) REFERENCES products_variations(id) ON DELETE CASCADE ON UPDATE CASCADE
      ) ENGINE=InnoDB;

      CREATE INDEX reviews_date ON reviews (date);
      CREATE INDEX reviews_rating ON reviews (rating);
      ');

        $this->upgradeOK();
    }

    public function check_ReviewsLangs()
    {
        return findmodule('reviews') && findModule(Modules::TRANSLATIONS) && $this->checkColumnExists('reviews', 'id_language');
    }

    /** Add languages to table reviews */
    public function upgrade_ReviewsLangs()
    {
        $langContext = \KupShop\KupShopBundle\Util\Compat\ServiceContainer::getService(\KupShop\KupShopBundle\Context\LanguageContext::class);

        sqlQuery("ALTER TABLE reviews ADD COLUMN id_language varchar(2) not null DEFAULT '{$langContext->getDefaultId()}'");

        $this->upgradeOK();
    }

    public function check_AddProductsFigureIndex()
    {
        return $this->checkIndexNameExists('products', 'figure');
    }

    /** Add index to products.figure and products_variations.figure */
    public function upgrade_AddProductsFigureIndex()
    {
        sqlQuery('ALTER TABLE products ADD INDEX figure (figure)');
        sqlQuery('ALTER TABLE products_variations ADD INDEX figure (figure)');

        $this->upgradeOK();
    }

    public function check_AddPhotosFigureIndex()
    {
        return $this->checkIndexNameExists('photos_articles_relation', 'show_in_lead');
    }

    /** Add index to photos_????_relation.figure */
    public function upgrade_AddPhotosFigureIndex()
    {
        //        sqlQuery('ALTER TABLE photos_products_relation ADD INDEX show_in_lead (show_in_lead)');
        sqlQuery('ALTER TABLE photos_articles_relation ADD INDEX show_in_lead (show_in_lead)');
        //        sqlQuery('ALTER TABLE photos_pages_relation ADD INDEX show_in_lead (show_in_lead)');

        $this->upgradeOK();
    }

    public function check_AddProductPriceIndex()
    {
        return $this->checkIndexNameExists('products', 'price');
    }

    /** Add index to product.price and product_variations.price */
    public function upgrade_AddProductPriceIndex()
    {
        sqlQuery('ALTER TABLE products ADD INDEX price (price)');
        sqlQuery('ALTER TABLE products_variations ADD INDEX price (price)');

        $this->upgradeOK();
    }
}
