<?php

namespace KupShop\ContentBundle\Resources\upgrade;

use Query\Operator;

class InfoPanelUpgrade extends \UpgradeNew
{
    public function check_createInfoPanelTable()
    {
        return $this->checkTableExists('info_panels');
    }

    /** info_panels: create table */
    public function upgrade_createInfoPanelTable()
    {
        sqlQuery('CREATE TABLE info_panels (
          id                    INT AUTO_INCREMENT                      NOT NULL,
          name                  VARCHAR(60)                             NOT NULL,
          type                  VARCHAR(50)         DEFAULT "default"   NOT NULL,
          active                ENUM("Y", "N")      DEFAULT "Y"         NOT NULL,
          version               INT                                     NOT NULL,
          date_from             DATETIME                                NULL,
          date_to               DATETIME                                NULL,
          body                  MEDIUMTEXT                              NULL,
          data                  LONGTEXT                                NULL,
          PRIMARY KEY (id)
        ) ENGINE = InnoDB');

        $infoPanel = sqlQueryBuilder()
            ->select('*')
            ->from('settings', 's')
            ->andWhere(Operator::equals(['key_name' => 'info_panel']))
            ->execute()
            ->fetchAssociative();

        if (($infoPanel ?? false) && !empty($infoPanel['value']) && $infoPanel['value'] != 'null') {
            $infoPanelValues = json_decode($infoPanel['value'], true);
            sqlQueryBuilder()
                ->insert('info_panels')
                ->directValues([
                    'name' => 'Informační panel',
                    'type' => 'default',
                    'active' => ($infoPanelValues['enable'] == 'Y') ? 1 : 0,
                    'date_from' => (!empty($infoPanelValues['date_from'])) ? $this->prepareDateTime($infoPanelValues['date_from']) : null,
                    'date_to' => (!empty($infoPanelValues['date_to'])) ? $this->prepareDateTime($infoPanelValues['date_to']) : null,
                    'body' => "{$infoPanelValues['text']}",
                    'version' => $infoPanelValues['version'],
                ])->execute();
        }

        $this->upgradeOK();
    }
}
