<?php

namespace KupShop\ContentBundle\Resources\upgrade;

use FilipSedivy\EET\Utils\UUID;
use Query\Operator;

class TemplatesUpgrade extends \UpgradeNew
{
    protected function isAllowed()
    {
        return findModule(\Modules::TEMPLATES);
    }

    public function check_blocksForTemplates()
    {
        return $this->checkColumnExists('templates', 'id_block');
    }

    /** Add id_block to templates and move content from templates.text to blocks */
    public function upgrade_blocksForTemplates()
    {
        sqlQuery('
           ALTER TABLE templates
              ADD COLUMN `id_block` int(11) UNSIGNED DEFAULT NULL,
              ADD CONSTRAINT `fk_templates_blocks` FOREIGN KEY (id_block) REFERENCES blocks(id)
                ON DELETE SET NULL ON UPDATE CASCADE;
        ');

        $translations = findModule(\Modules::TRANSLATIONS);

        $templates = sqlQueryBuilder()->select('*')->from('templates')->execute();
        foreach ($templates as $template) {
            // create root block and assign it to templates.id_block
            $this->insertSQL('blocks', []);
            $rootBlockID = sqlInsertId();
            $this->updateSQL('templates', ['id_block' => $rootBlockID], ['id' => $template['id']]);

            $uuid = UUID::v4();
            $blockObj = new \stdClass();
            $blockObj->type = 'legacy';
            $blockObj->id = $uuid;
            $settings = new \stdClass();
            $settings->html = $template['text'];
            $blockObj->settings = $settings;

            $json = json_encode([$blockObj]);

            $this->insertSQL('blocks', [
                'id_root' => $rootBlockID,
                'id_parent' => $rootBlockID,
                'position' => 1,
                'name' => $template['name'],
                'content' => $template['text'],
                'json_content' => $json,
            ]);
            $id_block = sqlInsertId();

            if ($translations) {
                $template_translations = sqlQuery('SELECT name, text, id_language, id_admin FROM templates_translations WHERE id_template='.$template['id']);
                foreach ($template_translations as $template_tr) {
                    $blockObj = new \stdClass();
                    $blockObj->type = 'legacy';
                    $blockObj->id = $uuid;
                    $settings = new \stdClass();
                    $settings->html = $template_tr['text'];
                    $blockObj->settings = $settings;

                    $json = json_encode([$blockObj]);

                    $this->insertSQL('blocks_translations', [
                        'id_block' => $id_block,
                        'id_language' => $template_tr['id_language'],
                        'id_admin' => $template_tr['id_admin'],
                        'name' => $template_tr['name'],
                        'content' => $template_tr['text'],
                        'json_content' => $json,
                    ]);
                }
            }
        }

        //        sqlQuery('ALTER TABLE templates DROP COLUMN `text`;');

        if ($translations) {
            //            sqlQuery('ALTER TABLE templates_translations DROP COLUMN `text`;');
        }

        $this->upgradeOK();
    }

    public function check_positionTemplates()
    {
        return $this->checkColumnExists('templates', 'position');
    }

    /** Add position and fill it with values */
    public function upgrade_positionTemplates()
    {
        sqlQuery('
               ALTER TABLE templates
                  ADD COLUMN `position` int(11) UNSIGNED DEFAULT NULL');

        $templates = sqlQueryBuilder()->select('id')->from('templates')->orderBy('id_category')->execute()->fetchAll();
        $position = 0;
        foreach ($templates as $template) {
            sqlQueryBuilder()->update('templates')
                ->directValues(['position' => $position])
                ->where(Operator::equals(['id' => $template['id']]))
                ->execute();
            $position++;
        }
        $this->upgradeOK();
    }

    public function check_trigger_Templates()
    {
        return $this->checkIfTriggerExists('trigger_templates');
    }

    /** Add trigger (incrementing position) to templates  */
    public function upgrade_trigger_Templates()
    {
        sqlQuery('CREATE TRIGGER trigger_templates BEFORE INSERT ON templates
                    FOR EACH ROW
                    BEGIN
                    IF NEW.position IS NULL THEN
                        SET NEW.position = (SELECT COALESCE(MAX(templates.position) + 1, 0) FROM templates WHERE id_category = NEW.id_category);
                    END IF;
                END;');
        $this->upgradeOK();
    }

    public function check_TemplateCatLabelsCol()
    {
        return $this->checkColumnExists('templates_categories', 'label');
    }

    /** templates_cagories: Add 'labels' column   */
    public function upgrade_TemplateCatLabelsCol()
    {
        sqlQuery("
        ALTER TABLE `templates_categories` ADD COLUMN `label` ENUM('')");

        $this->upgradeOK();
    }

    public function check_TemplateCatLabels()
    {
        if ($labels = findModule('templates', 'labels')) {
            return $this->checkEnumOptions('templates_categories', 'label', array_keys($labels));
        }

        return false;
    }

    /** templates_cagories: Add 'labels' column   */
    public function upgrade_TemplateCatLabels()
    {
        $this->updateEnumOptions(
            'templates_categories',
            'label',
            array_keys(findModule('templates', 'labels')));
        $this->upgradeOK();
    }

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

    /** templates_cagories: add data column */
    public function upgrade_dataColumn()
    {
        sqlQuery('ALTER TABLE templates_categories ADD COLUMN data MEDIUMTEXT DEFAULT NULL');

        $this->upgradeOK();
    }

    public function check_TemplatesDataColumn(): bool
    {
        return $this->checkColumnExists('templates', 'data');
    }

    /** templates: add data column */
    public function upgrade_TemplatesDataColumn(): void
    {
        sqlQuery('ALTER TABLE templates ADD COLUMN data MEDIUMTEXT DEFAULT NULL');

        $this->upgradeOK();
    }

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

    /** Add 'figure' column into templates table */
    public function upgrade_TemplatesFigureColumn()
    {
        sqlQuery('ALTER TABLE templates ADD COLUMN figure ENUM("Y", "N") DEFAULT "Y"');

        $this->upgradeOK();
    }
}
