<?php
/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class Controller extends CController
{
    /**
     * @var string the default layout for the controller view. Defaults to '//layouts/column1',
     * meaning using a single column layout. See 'protected/views/layouts/column1.php'.
     */
    public $layout = '//layouts/main';
    /**
     * @var array context menu items. This property will be assigned to {@link CMenu::items}.
     */
    public $menu = array();
    /**
     * @var array the breadcrumbs of the current page. The value of this property will
     * be assigned to {@link CBreadcrumbs::links}. Please refer to {@link CBreadcrumbs::links}
     * for more details on how to specify this property.
     */
    public $breadcrumbs = array();


    public $keywords = null;
    public $description = null;
    public $pageName;
    private $_pageTitle;
    public $headerGalleryId;
    public $sectionGalleryId;
    public $socialLinks;
    public $socialLinksSport;
    /** @var ContactForm */
    public $contactForm;
    public $siteData;
    private $_contacts;

    public function setSEOParams($title = null, $keywords = null, $description = null)
    {
        if ($title) $this->pageTitle = $title;
        if ($keywords) $this->keywords = $keywords;
        if ($description) $this->description = $description;
    }

    /**
     * @return string the page title. Defaults to the controller name and the action name.
     */
    public function getPageTitle()
    {
        if ($this->_pageTitle !== null)
            return $this->_pageTitle;
        else {
            if (!empty($this->pageName))
                $this->_pageTitle = $this->pageName . " | " . Yii::t('site', 'Авто лайф');
            else
                $this->_pageTitle = Yii::t('site', 'Авто лайф');
            return $this->_pageTitle;
        }
    }

    /**
     * @param string $value the page title.
     */
    public function setPageTitle($value)
    {
        $this->_pageTitle = $value;
    }


    /**
     * @param $section
     * @param $key
     * @return array
     */
    public function loadStaticPage($section, $key)
    {
        /** @var $page StaticPage */
        $page = StaticPage::modelByPk($section, $key);
        $this->pageName = $page->i18n->name;
        $this->setSEOParams($page->i18n->title, $page->i18n->keywords, $page->i18n->description);
        return $page->getDataAttributes() + $page->i18n->getDataAttributes();
    }

    public function init()
    {
        parent::init();
        /** @var $dataModel StaticData */
        $dataModel = StaticData::model()->with('i18n')->findByPk(array('section' => 'site', 'key' => 'general'));
//        CVarDumper::dump($dataModel->i18n,10,true); exit();
        $this->siteData = $dataModel->getDataAttributes() + $dataModel->i18n->getDataAttributes();

        $this->headerGalleryId = $this->siteData['gallery_id'];
        $this->socialLinks = $this->siteData['social_links'];
        $this->socialLinksSport = $this->siteData['social_links_sport'];


    }

    protected function beforeAction($action)
    {
        $res = parent::beforeAction($action);
        if ($res) {

            $this->contactForm = new ContactForm();
            if (isset($_POST['ContactForm'])) {
                Yii::app()->request->validateCsrfToken(null);
                $this->contactForm->setAttributes($_POST['ContactForm']);
                $route =  $this->id . '/' . $this->action->id;
                $disabledRoutes = array(
                    'sport/index',
                    'site/index',
                    'calendarSection/calendar',
                    'albumsSection/albums',
                    'albumsSection/album',
                    'warranty/index',
                    'site/contact',
                );
                if ($this->contactForm->validate() && empty($this->contactForm->link) && (!in_array($route, $disabledRoutes))) {
                    /** @var $contact Contact */
                    $contact = Contact::model()->findByPk($this->contactForm->contact);
                    /** @var $mailer Swift_Mailer */
                    $mailer = Yii::app()->swiftMailer->getMailer();
                    $message = Swift_Message::newInstance();
                    $message->setReplyTo($this->contactForm->email);
                    $message->setFrom('site@auto-life.ua');
                    $message->setTo($contact->email);
                    $args = Swift_DependencyContainer::getInstance()
                        ->createDependenciesFor('mime.message');
                    /** @var $grammar Swift_Mime_Grammar */
                    $grammar = $args[3];
                    if (isset($this->siteData['bcc_emails']) && (!empty($this->siteData['bcc_emails'])))
                        foreach (explode(',', $this->siteData['bcc_emails']) as $e)
                            if (preg_match('/^' . $grammar->getDefinition('addr-spec') . '$/D', $e))
                                $message->addBcc($e);
                    if (!empty($contact->bcc_email))
                        foreach (explode(',', $contact->bcc_email) as $e) {
                            if (preg_match('/^' . $grammar->getDefinition('addr-spec') . '$/D', $e))
                                $message->addBcc($e);
                        }
                    $message->setSubject('Вопрос, c сайта Авто-лайф');
                    $message->setBody(
                        "Имя: {$this->contactForm->name}\r\n" .
                            "E-Mail: {$this->contactForm->email}\r\n" .
                            "Контактный номер: {$this->contactForm->phone}\r\n" .
                            "Текст вопроса: {$this->contactForm->body}\r\n" .
                            "\r\nОтправлено со страницы: " . Yii::app()->getBaseUrl(true) . Yii::app()->request->getUrl());

                    $mailer->send($message);
                    Yii::app()->user->setFlash('contact', Yii::t('site', 'ВАШ ЗАПРОС УСПЕШНО ОТПРАВЛЕН! <br/>
Благодарим Bас за уделенное время, мы постараемся максимально быстро и оперативно ответить Вам.'));
                    //$this->refresh();
                }
            }
        }
        return $res;
    }

    /** @return GalleryPhoto[] */
    public function getHeaderPhotos()
    {
        $criteria = new CDbCriteria();
        $criteria->condition = 'gallery_id = :gallery_id';
        $criteria->params[':gallery_id'] = $this->sectionGalleryId;
        $criteria->order = 'rand()';
        $r1 = GalleryPhoto::model()->findAll($criteria);
        if (count($r1) > 0) return $r1;
        $criteria->params[':gallery_id'] = $this->headerGalleryId;
        return GalleryPhoto::model()->findAll($criteria);
    }

    public function setContacts($contacts, $force = false)
    {
        if (empty($contacts)) return;
        foreach ($contacts as $k => $v) {
            if (empty($v)) unset($contacts[$k]);
        }
        if (count($contacts) > 0 && ($this->_contacts === null || $force))
            $this->_contacts = $contacts;
    }

    public function getContacts()
    {
        $contacts = array();
        if (isset($this->_contacts) && (!empty($this->_contacts))) {
            $criteria = new CDbCriteria();
            $criteria->alias = 't';
            $criteria->addInCondition('t.id', $this->_contacts);
            $criteria->index = 'id';
            $data = Contact::model()->with('i18n')->findAll($criteria);
            foreach ($this->_contacts as $id) {
                if (isset($data[$id])) $contacts[] = $data[$id];
            }
        }
        return $contacts;
    }

}