<?php

namespace frontend\controllers;

use core\services\ContactService;
use frontend\components\FrontendController;
use Yii;
use core\forms\ContactForm;

class ContactController extends FrontendController
{
    public $layout = 'blank';

    private $_service;

    public function __construct($id, $module, ContactService $service, $config = [])
    {
        parent::__construct($id, $module, $config);
        $this->_service = $service;
    }

    public function actionIndex()
    {
        $form = new ContactForm();
        if ($form->load(Yii::$app->request->post()) && $form->validate()) {
            try {
                $this->_service->send($form);
                Yii::$app->session->setFlash('success', Yii::t('main', 'Thank you for contacting us. We will respond to you as soon as possible.'));

                return $this->goHome();
            } catch (\Exception $e) {
                Yii::$app->errorHandler->logException($e);
                Yii::$app->session->setFlash('error', Yii::t('main', 'There was an error sending your message.'));
            }

            return $this->refresh();
        }

        return $this->render('index', [
            'model' => $form,
        ]);
    }
}