<?php

namespace common\modules\triggers\models;

use Yii;
use common\modules\messageTemplate\models\MessageTemplate;
use common\modules\messageTemplate\components\Templates;
use common\components\UnisenderAPI;
use yii\helpers\Json;

/**
 * This is the model class for table "trigger_schedule".
 *
 * @property integer $id
 * @property integer $sended
 * @property integer $checked
 * @property integer $message_id
 * @property string $message
 * @property string $email
 * @property string $time
 * @property string $date_create
 * @property integer $list_id
 * @property integer $campaign_id
 * @property integer $template_id
 * @property integer $trigger_id
 */
class TriggerSchedule extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'trigger_schedule';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['sended', 'checked', 'message_id', 'list_id', 'campaign_id', 'trigger_id', 'template_id'], 'integer'],
            [['message', 'email', 'template_id', 'trigger_id'], 'required'],
            [['message'], 'string'],
            [['time', 'date_create'], 'safe'],
            [['email'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'sended' => 'Sended',
            'checked' => 'Checked',
            'message_id' => 'Message ID',
            'message' => 'Message',
            'email' => 'Email',
            'time' => 'Time',
            'date_create' => 'Date Create',
            'list_id' => 'List ID',
            'campaign_id' => 'Campaign ID',
        ];
    }

    public static function sendMessage($email, $template_id, $templateData, $trigger_id=null)
    {
        $time_now=new \DateTime();
        /** @var MessageTemplate $templateModel */
        $templateModel = MessageTemplate::findOne($template_id);
        /** @var Templates $template */

        $template = new Templates($template_id, $templateData);
        $sender = new UnisenderAPI();
        // Create the send list
        $newList = $sender->createList();
        $newListObject=Json::decode($newList);
        if (array_key_exists('result', $newListObject) && is_array($newListObject['result']) && array_key_exists('id', $newListObject['result'])) {
            $newListId=$newListObject['result']['id'];
            // Subscribe user to new List
            $sender->subscribe(['list_ids' => $newListId, 'fields[email]' => $email, 'double_optin' => 1]);
            // Create new message
            $newMessage=$sender->createEmailMessage('Школа аналитики "Арт Проект"', 'subscribe@task-on.com', $templateModel->subject, $template->getTemplate(), $newListId);
            // Decode result
            $newMessageObject=Json::decode($newMessage);
            if (array_key_exists('result', $newMessageObject) && is_array($newMessageObject['result']) && array_key_exists('message_id', $newMessageObject['result'])) {
                // Get the message ID
                $newMessageId=$newMessageObject['result']['message_id'];
                // Create new campaign
                $newCampaign = $sender->createCampaign($newMessageId);
                // Parse the result
                $newCampaignObject = Json::decode($newCampaign);
                if (array_key_exists('result', $newCampaignObject) && is_array($newCampaignObject['result']) && array_key_exists('campaign_id', $newCampaignObject['result'])) {
                    $newCampaignId = $newCampaignObject['result']['campaign_id'];

                    $schedule = new TriggerSchedule();
                    $schedule->sended=1;
                    $schedule->template_id=$template_id;
                    $schedule->trigger_id=$trigger_id;
                    $schedule->message_id=$newMessageId;
                    $schedule->message=$template->getTemplate();
                    $schedule->email=$email;
                    $schedule->time=$time_now->format('Y-m-d H:i:s');
                    $schedule->date_create=$time_now->format('Y-m-d H:i:s');
                    $schedule->list_id=$newListId;
                    $schedule->campaign_id=$newCampaignId;
                    if ($schedule->save()) {
                        return true;
                    } else {
                        return (current(current($schedule->getErrors())));
                    }
                } else {
                    $error = (array_key_exists('error', $newCampaignObject)) ? $newCampaignObject['error'].' (createCampaign)' : 'Неизвестная ошибка (CreateCampaign)';
                    return $error;
                }
            } else {
                $error = (array_key_exists('error', $newMessageObject)) ? $newMessageObject['error'].' (createMessage)' : 'Неизвестная ошибка (CreateMessage)';
                return $error;
            }
        } else {
            $error = (array_key_exists('error', $newListObject)) ? $newListObject['error'].' (createList)' : 'Неизвестная ошибка (CreateList)';
            return $error;
        }
    }
}
