<?php

$main_class = 'MailerLiteActions';

use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\MailerLiteBundle\MailerLite;

class MailerLiteActions extends Window
{
    protected $action;
    protected $ID;

    protected $template = 'window/mailerLiteActions.tpl';
    protected $title = 'MailerLiteActions';

    /**
     * @var MailerLite
     */
    protected $mailerlite;

    public function __construct()
    {
        ini_set('memory_limit', '1G');
        $this->mailerlite = ServiceContainer::getService(MailerLite::class);
        $this->mailerlite->getSubscriberGroup();
    }

    public function get_vars()
    {
        if ($this->mailerlite->error) {
            $vars['ErrStr'] = $this->mailerlite->error;

            return $vars;
        }

        $vars = parent::get_vars();
        $this->ID = $this->getID();
        $this->action = $this->getAction();
        if ($this->action == 'Upgrade') {
            $this->title = 'MailerLite - Upgrade ';
            $upgrade = false;
            if ($this->ID == 'UpgradeCustomFields') {
                $this->title .= 'Custom Fields';
                $upgrade = $this->mailerlite->upgradeCustomFields();
            }
            if ($this->ID == 'UpgradeWebhooks') {
                $this->title .= 'Webhooks';
                $upgrade = $this->mailerlite->upgradeWebhooks();
            }
            $vars['body']['upgrade'] = ($upgrade ? 'OK' : $upgrade);
            $vars['body']['upgrade_message'] = ($this->mailerlite->upgrade_message ?? []);
        }
        if ($this->action == 'Synchronize') {
            $this->title = 'MailerLite - Synchronization';
            $sync_data = null;
            if ($this->ID == 'SyncEverything') {
                $sync_data = $this->mailerlite->Synchronize();
            }
            if ($this->ID == 'Synchronize') {
                $now = time();
                $filter_date = date('Y-m-d', $now - 7 * 24 * 60 * 60); // -7 days
                $sync_data = $this->mailerlite->Synchronize($filter_date);
                $sync_data['period'] = $filter_date.' - '.date('Y-m-d', $now);
            }
            $vars['body']['sync_data'] = $sync_data;
        }

        $vars['body']['type'] = $this->getID();
        $vars['body']['acn'] = $this->action;
        $vars['body']['title'] = $this->title;

        return $vars;
    }
}
