<?php

namespace Mnv\Admin\Controllers;

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

use Mnv\Core\AdminMnv;

use Mnv\Models\FAQ;

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

	public function fetch()
    {

        $faq = new FAQ($this->request);

        $this->smarty->assign('activeItem','faqs');
        $this->smarty->assign('title', 'FAQ');


        if ($this->action == 'remove') {
            $result = $faq->remove()
                ? array('status' => 200, 'message' => 'Вопрос удален', 'type' => 'success')
                : array('status' => 403, 'message' => 'Ошибка при удаление вопроса', 'type' => 'error');

            response()->json($result, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
            exit();
        }
        else if ($this->action == 'status') {
            $result = $faq->status()
                ? array('data' => true, 'status' => $faq->status, 'type' => 'success')
                : array('data' => false, 'status' => $faq->status, 'type' => 'error');

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

        }
        else if ($this->action == 'reorder') {
            $i = 0;
            foreach ($faq->faqIds as $faqId) {
                $i++;
                $faq->id = $faqId;
                $faq->data['orderBy'] = $i;
                $faq->update($faq->data);
            }

            response()->json(array('status' => 200), \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
            exit;
        }

        $faqs = collect($faq->all($this->limit, $this->page))->map(function ($item) {
            $item['statusName']  = lang('general:statuses:' . $item['status']);

            return $item;
        })->all();

        $faq->total();
        $pages = getPageNums($faq->total, $this->page, $this->limit, 0, 4, 4, 0);

        $this->smarty->assign('totalFaqs', $faq->total);
        $this->smarty->assign('faqs',  $faqs);
        $this->smarty->assign('pageNums', $pages);

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

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

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

    }

}