<?php

namespace KupShop\ContentBundle\Resources\upgrade;

use Query\Operator;

class EmailUpgrade extends \UpgradeNew
{
    public function __construct($verbose = self::VERBOSE_NO, $useLocalUpgrades = self::LOCAL_UPGRADES_YES)
    {
        parent::__construct($verbose, $useLocalUpgrades);
    }

    public function check_trigger_emails()
    {
        return $this->checkIfTriggerExists('trigger_emails');
    }

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

    public function check_unique()
    {
        return $this->checkIndexNameExists('emails', 'emails_type_name_uindex');
    }

    /** Add UNIQUE index to emails  */
    public function upgrade_unique()
    {
        sqlQuery('UPDATE emails SET name = "" WHERE name IS NULL');
        sqlQuery('ALTER TABlE emails MODIFY name VARCHAR(250) DEFAULT "" NOT NULL');
        sqlQuery('CREATE UNIQUE INDEX emails_type_name_uindex ON emails (type, name)');

        $this->upgradeOK();
    }

    public function check_emailsEnabledColumn()
    {
        return $this->checkColumnExists('emails', 'enabled');
    }

    /** Add `enabled` column to `emails` */
    public function upgrade_emailsEnabledColumn()
    {
        sqlQuery("ALTER TABLE emails ADD COLUMN enabled ENUM('Y', 'N') DEFAULT 'Y' NOT NULL");
        $disabled = [];
        $dbcfg = \Settings::getDefault();
        if (($dbcfg['order_send_received_mail'] ?? 'N') == 'N') {
            $disabled[] = 'ORDER_CREATE';
        }
        if (($dbcfg['order_send_status_mail'] ?? 'N') == 'N') {
            $disabled[] = 'ORDER_STATUS_CHANGE';
        }
        if (($dbcfg['order_send_to_shopkeeper'] ?? 'N') == 'N') {
            $disabled[] = 'ORDER_CREATE_ADMIN';
        }
        if ($disabled) {
            sqlQueryBuilder()->update('emails')
                ->directValues(['enabled' => 'N'])
                ->andWhere(Operator::inStringArray($disabled, 'type'))
                ->execute();
        }

        $this->upgradeOK();
    }
}
