<?php

namespace Mnv\Admin\Controllers;

if (!defined('MNV_CMS')) {
    die('Hacking attempt!');
}

use Mnv\Core\AdminMnv;
use Mnv\Core\Feedback;
use Mnv\Models\Users\UserTypes;

/**
 * Class SubscribeAdmin
 * @package Mnv\Admin\Controllers
 */
class SubscribeAdmin extends AdminMnv
{

    private $step = 0;

    public function fetch()
    {
        $feedback = new Feedback();
        $startFrom = 0;
        $count = 0;

        $this->smarty->assign('activeItem', 'subscribe');
        $this->smarty->assign('title', 'Рассылка письма');

        $subject      = $this->request->get('subject', '');
        $message      = $this->request->get('message');
        $startFrom    = $this->request->get('startFrom');

//        var_dump($subject);
        if  ($this->action == 'send') {
            if (empty($subject)) $this->errors['subject_empty'] = "Тема письма не должна быть пустой";
            if (empty($message)) $this->errors['message_empty'] = "Текст письма не должна быть пустой";

            if (empty($this->errors)) {
                $subscribers = connect()->table('subscribe')->select('email, phone')->limit($this->limit)->offset($startFrom)->getAll();

                if ($this->config['mail_transport'] == 'smtp') {
                    foreach ($subscribers as $subscriber) {
                        $feedback->send($subscriber->email, "", $subject, $message, "");
                        $this->step++;
                    }
                }

                $count = $startFrom + $this->step;
            }

            if (empty($this->errors)) {
                $this->response = array('status' => 200, 'count' => $count);
            } else  {
                $this->response = array('status' => 403, 'message' => $this->errors);
            }

            response()->json($this->response, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'])->send();

        } else {
                $subscribers = connect()->table('users')->count('*', 'count')->where('subscribe', 'yes')->where('status', 1)->where('accessLevel',UserTypes::SUBSCRIBER)->getValue();

                $this->smarty->assign('total', $subscribers);
        }



        if ($this->permissions('subscribe')) {
            return $this->smarty->fetch('views/subscribe/subscribe.tpl');
        }

        $this->smarty->assign('title', 'Access Denied');
        return $this->smarty->fetch('accessIsDenied.tpl');


    }
}
