<?php
    /**
     * Created by PhpStorm.
     * User: yarik
     * Date: 12.06.17
     * Time: 11:21
     */
    
    namespace frontend\models;
    
    use yii\base\Model;
    use yii\helpers\Json;
    use yii\helpers\Url;
    
    class ShareBasket extends Model
    {
        public $email;
        public $url = 'site/get-basket';
        public $from = 'artbox@artbox.dev';
        
        /**
         * @inheritdoc
         */
        public function rules()
        {
            return [
                [
                    [
                        'email',
                    ],
                    'email',
                ],
                [
                    [
                        'email',
                    ],
                    'required',
                ],
            ];
        }
        
        public function attributeLabels()
        {
            return [
                'email' => \Yii::t('app', 'Поделиться корзиной'),
            ];
        }
        
        public function send()
        {
            /**
             * @var \artbox\order\models\Basket $basket
             */
            $basket = \Yii::$app->get('basket');
            $data = $basket->getData();
            if (empty($data)) {
                return [
                    'success' => false,
                    'msg'     => \Yii::t('app', 'Basket is empty'),
                ];
            }
            $dataArray = [];
            foreach ($data as $variantId => $item) {
                $dataArray[ $variantId ] = $item[ 'count' ];
            }
            $dataString = Json::encode($dataArray);
            $url = Url::to(
                [
                    $this->url,
                    'items' => $dataString,
                ],
                true
            );
            if (\Yii::$app->mailer->compose(
                [ 'html' => 'shareBasket' ],
                [
                    'url' => $url,
                ]
            )
                                  ->setFrom($this->from)
                                  ->setTo($this->email)
                                  ->setSubject(\Yii::t('app', 'Shared basket'))
                                  ->send()
            ) {
                return [
                    'success' => true,
                    'msg'     => \Yii::t('app', 'Email successfully sent.'),
                ];
            } else {
                return [
                    'success' => false,
                    'msg'     => \Yii::t('app', 'Email cannot be send.'),
                
                ];
            }
        }
    }