<?php

class Upgrade39 extends UpgradeNew
{
    public function checkRightfulness_blocksForSections()
    {
        return $this->checkColumnExists('sections', 'id_block');
    }

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

        $sections = sqlQueryBuilder()->select('*')->from('sections')->execute();
        foreach ($sections as $section) {
            // crate root block and assign it to sections.id_block
            $this->insertSQL('blocks', []);
            $rootBlockID = sqlInsertId();
            $this->updateSQL('sections', ['id_block' => $rootBlockID], ['id' => $section['id']]);
            $this->insertSQL('blocks', [
                'id_root' => $rootBlockID,
                'id_parent' => $rootBlockID,
                'position' => 1,
                'name' => $section['name'],
                'content' => $section['descr'],
            ]);
        }

        sqlQuery('ALTER TABLE sections
            DROP COLUMN `descr`;');

        $this->upgradeOK();
    }

    public function checkRightfulness_largerAndUniqueParameterName()
    {
        return $this->checkColumnType('parameters', 'name', 'varchar(100)');
    }

    /** Make parameters.name larger and unique */
    public function makeChanges_largerAndUniqueParameterName()
    {
        sqlQuery("
           ALTER TABLE parameters
              MODIFY COLUMN `name` varchar(100) default '' not null;
            CREATE UNIQUE INDEX parameters_name_uindex ON parameters (name);
        ");

        $this->upgradeOK();
    }
}
