<?php

namespace Mnv\Admin\Controllers;

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

use Mnv\Core\AdminMnv;

use Mnv\Models\Comments;

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

    public function fetch()
    {

        $comment = new Comments($this->request);

        $this->smarty->assign('activeItem','comments');
        $this->smarty->assign('title', lang('comments:title'));
        /** statuses */
        $this->smarty->assign('statuses', array_slice(lang('comments:statuses'), 1));


        if ($this->action == 'edit') {
            $comment->edit()->gettingInfoAboutUsers();
            if (empty($comment->data)) $this->errors['comment_not_found'] = true;

        } else if ($this->action == 'save' || $this->action == 'apply') {
            $comment->data['authorName']  = trim($comment->data['authorName']);
            $comment->data['content']     = trim($comment->data['content']);

            /* checking fields */
            if (empty($comment->data['authorName'])) $this->errors['authorName'] = true;

//          if (empty($comment->data['authorEmail'])) $this->errors['authorEmail'] = true;
//          if (!empty($comment->data['authorEmail']) && !isValidEmail($comment->data['authorEmail'])) $this->errors['authorEmailNot'] = true;

            if (empty($comment->data['content'])) $this->errors['content'] = true;

            if (empty($this->errors)) {

                if ($comment->prepare($comment->data, $this->manager['userId'])) {
                    $this->messages['saved'] = true;
                } else {
                    $this->errors['not_saved'] = true;
                }
            }

            $comment->edit()->gettingInfoAboutUsers();

            if (empty($this->errors) && $this->action === 'save') {
                redirect($this->adminUrl . "/comments?" . $this->buildQueryString(['page' => $this->page]));
            }
        }


        $this->smarty->assign('comment', $comment->data);


        if (!empty($this->errors)) {
            $this->smarty->assign('errors', $this->errors);
        }
        if (!empty($this->messages)) {
            $this->smarty->assign('messages', $this->messages);
        }

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

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

    }

}