<?php

class Upgrade40 extends UpgradeNew
{
    public function check_PriceLevelsRanges()
    {
        return findModule(\Modules::PRICE_LEVELS) && $this->checkTableExists('price_levels_ranges');
    }

    /** Create table for price_level ranges*/
    public function upgrade_PriceLevelsRanges()
    {
        sqlQuery(" CREATE TABLE IF NOT EXISTS price_levels_ranges (
              id_price_level INT(10) UNSIGNED NOT NULL,
              range_from INT(11) NOT NULL,
              range_to INT(11) NOT NULL,
              discount float default '0' not null,
              unit enum('perc', 'price', 'final_price') default 'perc' not null
            ) ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4;         
                       
           ALTER TABLE price_levels_ranges ADD FOREIGN KEY (`id_price_level`) REFERENCES `price_levels`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
        ");

        $this->upgradeOK();
    }

    public function check_InnoDBMargins()
    {
        return findModule(\Modules::PRICE_LEVELS) && $this->checkIsInnoDB('price_levels_ranges');
    }

    /** Fix innodb instead myisam*/
    public function upgrade_InnoDBMargins()
    {
        sqlQuery('ALTER TABLE price_levels_ranges ENGINE = InnoDB;');
    }

    public function check_EmailsTable()
    {
        return $this->checkTableExists('emails');
    }

    /** Create table emails*/
    public function upgrade_EmailsTable()
    {
        sqlQuery(' CREATE TABLE IF NOT EXISTS emails (
              id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,              
              order_status INT(11) DEFAULT NULL,
              type VARCHAR(250) NOT NULL,
              position INT(11) DEFAULT NULL,
              body TEXT NOT NULL,
              subject VARCHAR(250) DEFAULT NULL,
              name VARCHAR(250) DEFAULT NULL,
              email VARCHAR(250),
              sms TEXT DEFAULT NULL
            ) ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4;
        ');

        $settings = Settings::createFromDB();

        if ($settings->getOrderMessages()) {
            foreach ($settings->getOrderMessages() as $name => &$message) {
                $this->insertSQL('emails', [
                    'order_status' => (empty($message['status'])) ? null : $message['status'],
                    'subject' => $message['subject'],
                    'name' => $name,
                    'body' => $message['text'],
                    'type' => \KupShop\KupShopBundle\Email\OrderMessageEmail::getType(),
                ]);
            }
        }

        $this->insertSQL('emails', [
            'subject' => $settings->getOrderReceivedSubject(),
            'body' => $settings->getOrderReceivedText(),
            'type' => \KupShop\KupShopBundle\Email\OrderCreateEmail::getType(),
        ]);

        $this->insertSQL('emails', [
            'email' => $settings->order_from_mail,
            'subject' => 'Šablona emailu',
            'body' => $settings->getOrderTemplateText(),
            'type' => \KupShop\KupShopBundle\Email\BaseEmail::getType(),
        ]);

        $this->insertSQL('emails', [
            'subject' => $settings->getOrderStatusSubject(),
            'body' => $settings->getOrderStatusText(),
            'type' => \KupShop\KupShopBundle\Email\OrderChangeEmail::getType(),
        ]);

        $this->upgradeOK();
    }

    public function check_DefaultOrdering()
    {
        return $this->checkColumnDefault('sections', 'orderby', 'title');
    }

    /** Set producer/section default ordering to 'title' */
    public function upgrade_DefaultOrdering()
    {
        sqlQuery("ALTER TABLE sections ALTER COLUMN orderby SET DEFAULT 'title'");
        sqlQuery("ALTER TABLE producers ALTER COLUMN orderby SET DEFAULT 'title'");
    }

    public function check_SectionGoogleFeed()
    {
        if (Settings::getDefault()->user_rights_version == 3) {
            $this->commitDataMigration(4);
        }

        return false;
    }

    /** Fix Google feed*/
    public function upgrade_SectionGoogleFeed()
    {
        sqlGetConnection()->transactional(function () {
            sqlQuery('UPDATE sections s LEFT JOIN kupshop_shared.feed_google f ON f.id_old = s.feed_google SET s.feed_google = f.id');

            $query = sqlQuery('SELECT id,name FROM sections s WHERE s.feed_google = 0');
            $zero = sqlNumRows($query);

            if ($zero != 0) {
                sqlQuery('UPDATE sections SET feed_google = NULL WHERE feed_google = 0');
                var_dump($query->fetchAll());
            }

            $this->commitDataMigration(4);

            $this->upgradeOK();
        });
    }

    public function check_Settings__table()
    {
        return !$this->checkTableExists('settings__');
    }

    /** Remove settings__ table */
    public function upgrade_Settings__table()
    {
        sqlQuery('DROP TABLE settings__');
        $this->upgradeOK();
    }

    public function check_AddRemoveFromSet()
    {
        return $this->checkFunctionExists('ADD_TO_SET');
    }

    /** Add ADD_TO_SET and REMOVE_FROM_SET database functions */
    public function upgrade_AddRemoveFromSet()
    {
        sqlQuery("CREATE FUNCTION IF NOT EXISTS ADD_TO_SET(`member` VARCHAR(64), `set` VARCHAR(4096))
              RETURNS VARCHAR(4096)
              COMMENT 'ADD_TO_SET(member, set)\nAdds member to a SET string'
            DETERMINISTIC NO SQL
              RETURN CONCAT_WS(',', IF(`set` = '', NULL, `set`), `member`)");

        sqlQuery("CREATE FUNCTION IF NOT EXISTS REMOVE_FROM_SET(`member` VARCHAR(64), `set` VARCHAR(4096))
              RETURNS VARCHAR(4096)
              COMMENT 'REMOVE_FROM_SET(member, set)\nRemoves member from a SET string'
            DETERMINISTIC NO SQL
              RETURN TRIM(BOTH ',' FROM
                          REPLACE(CONCAT(',', `set`, ','), CONCAT(',', `member`, ','), ',')
              )");

        $this->upgradeOK();
    }

    public function check_AddIdToSectionProducer()
    {
        return $this->checkColumnExists('section_producer', 'id');
    }

    /** Add id column to section producer */
    public function upgrade_AddIdToSectionProducer()
    {
        sqlQuery('alter table section_producer add unique key `id_section_producer_uk` (`id_section`, `id_producer`);
                ALTER TABLE section_producer DROP PRIMARY KEY;
                
                ALTER TABLE section_producer ADD id INT(11) PRIMARY KEY AUTO_INCREMENT FIRST;
        ');

        $this->upgradeOK();
    }

    public function check_addTablePhotosProducers()
    {
        return $this->checkTableExists('photos_producers_relation');
    }

    /** Add photos to producer */
    public function upgrade_addTablePhotosProducers()
    {
        sqlQuery("create table photos_producers_relation
            (
              id_photo int default '0' not null,
              id_producer int(11) UNSIGNED default '0' not null,
              show_in_lead enum('Y', 'N') default 'N' not null,
              active enum('Y', 'N') default 'Y' not null,
              date_added datetime default '0000-00-00 00:00:00' not null,
              position int null,
              primary key (id_photo, id_producer),
              constraint photos_producers_relation_ibfk_1
              foreign key (id_producer) references producers (id)
                on update cascade on delete cascade
            );
            
            create index photos_producers_relation_ibfk_2
                on photos_producers_relation (id_producer)
            ;
            
            create index photos_producers_relation_ibfk_1
                on photos_producers_relation (show_in_lead)
            ;
        ");

        $this->upgradeOK();
    }

    public function check_addTableDeliveryZasilkovna()
    {
        return $this->checkTableExists('delivery_zasilkovna', 'kupshop_shared');
    }

    /** Add table delivery_zasilkovna */
    public function upgrade_addTableDeliveryZasilkovna()
    {
        sqlQuery('create table kupshop_shared.delivery_zasilkovna
                (
                    id int primary key,
                    zip int(5) ZEROFILL null,
                    data text null,
                    hours text null,
                    street varchar(100) null,
                    country varchar(50) null,
                    city varchar(50) null,
                    name varchar(50) null,
                    place varchar(50) null,
                    labelRouting varchar(50) null,
                    url varchar(250) null,
                    directions text null
                );
        ');

        $this->upgradeOK();
    }

    public function check_addTableDeliveryUrgentCargus()
    {
        return $this->checkTableExists('delivery_ro_regions', 'kupshop_shared');
    }

    /** Add table delivery_ro_regions */
    public function upgrade_addTableDeliveryUrgentCargus()
    {
        sqlQuery('create table kupshop_shared.delivery_ro_regions
                (
                    id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,  
                    county VARCHAR(60) NOT NULL,
                    city VARCHAR(60) NOT NULL
                );
        ');

        $this->upgradeOK();
    }

    public function check_InnoDBDiscounts()
    {
        return findModule('purchase_discounts') && $this->checkIsInnoDB('discounts');
    }

    /** Discounts: Fix innodb instead myisam */
    public function upgrade_InnoDBDiscounts()
    {
        sqlQuery('ALTER TABLE discounts ENGINE = InnoDB;');
        $this->upgradeOK();
    }

    public function check_PhotosSyncIdField()
    {
        return $this->checkColumnExists('photos', 'sync_id');
    }

    /** Add Photos sync_id field, remove author, image_1 */
    public function upgrade_PhotosSyncIdField()
    {
        sqlQuery('ALTER TABLE photos ADD COLUMN sync_id TEXT');
        sqlQuery('UPDATE photos SET sync_id=descr');
        sqlQuery('ALTER TABLE photos DROP COLUMN author, DROP COLUMN image_1');
        $this->upgradeOK();
    }

    public function check_utfAbraComplementModel()
    {
        return findModule('abra') && $this->checkColumnCollation('abra_complement_models', 'name', 'utf8mb4_general_ci') && !$this->checkTableExists('abra_complement_models');
    }

    /** abra_complement_models COLLATION to utf8mb4_general_ci */
    public function upgrade_utfAbraComplementModel()
    {
        sqlQuery('ALTER TABLE abra_complement_models MODIFY name VARCHAR(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci');

        $this->upgradeOK();
    }

    public function check_utfAbraSeries()
    {
        return findModule('abra') && !$this->checkTableExists('abra_series') && $this->checkColumnCollation('abra_series', 'name', 'utf8mb4_general_ci');
    }

    /** abra_series COLLATION to utf8mb4_general_ci */
    public function upgrade_utfAbraSeries()
    {
        sqlQuery('ALTER TABLE abra_series MODIFY name VARCHAR(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci');
        sqlQuery('ALTER TABLE abra_series MODIFY descr LONGTEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci');

        $this->upgradeOK();
    }

    public function check_strip_tags()
    {
        return $this->checkFunctionExists('STRIP_TAGS');
    }

    /** Add STRIP_TAGS database function */
    public function upgrade_strip_tags()
    {
        sqlQuery("CREATE FUNCTION IF NOT EXISTS STRIP_TAGS(str text) RETURNS text
        DETERMINISTIC NO SQL
  BEGIN
    DECLARE start, end INT DEFAULT 1;
    LOOP
      SET start = LOCATE('<', str, start);
      IF (!start) THEN RETURN str; END IF;
      SET end = LOCATE('>', str, start);
      IF (!end) THEN SET end = start; END IF;
      SET str = INSERT(str, start, end - start + 1, '');
    END LOOP;
  END;");

        $this->upgradeOK();
    }

    public function check_GreetingName()
    {
        return $this->checkIndexNameExists('kupshop_shared.greeting_name', 'greeting_name__index');
    }

    /** Change kupshop_shared.greeting_name INDEX */
    public function upgrade_GreetingName()
    {
        if (!$this->checkIndexNameExists('kupshop_shared.greeting_name', 'PRIMARY')) {
            sqlQuery('ALTER TABLE kupshop_shared.greeting_name DROP PRIMARY KEY');
        }
        sqlQuery('ALTER TABLE kupshop_shared.greeting_name MODIFY original VARCHAR(25) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci');
        sqlQuery('CREATE INDEX greeting_name__index ON kupshop_shared.greeting_name (original, sex);');

        $this->upgradeOK();
    }

    public function check_GreetingSurname()
    {
        return $this->checkIndexNameExists('kupshop_shared.greeting_surname', 'greeting_surname__index');
    }

    /** Change kupshop_shared.greeting_surname INDEX */
    public function upgrade_GreetingSurname()
    {
        if (!$this->checkIndexNameExists('kupshop_shared.greeting_surname', 'PRIMARY')) {
            sqlQuery('ALTER TABLE kupshop_shared.greeting_surname DROP PRIMARY KEY');
        }
        sqlQuery('ALTER TABLE kupshop_shared.greeting_surname MODIFY original VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci');
        sqlQuery('CREATE INDEX greeting_surname__index ON kupshop_shared.greeting_surname (original, sex);');

        $this->upgradeOK();
    }
}
