<?php

namespace Mnv\Admin\Controllers;

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

use Mnv\Core\AdminMnv;

use Mnv\Models\Socials;

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

    public function fetch()
    {
        $social = new Socials($this->request);

        $this->smarty->assign('activeItem','socials');
        $this->smarty->assign('title', lang('settings:social'));


        if  ($this->action == 'remove') {
            $result = $social->remove()
                ? array('status' => 200, 'message' => lang('socials:messages:1'), 'type' => 'success')
                : array('status' => 403, 'message' => lang('socials:errors:2'), '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 = $social->status()
                ? array('data' => true, 'status' => $social->status, 'type' => 'success')
                : array('data' => false, 'status' => $social->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;
            $social->data = [];
            foreach ($social->socialIds as $socialId) {
                $i++;
                $social->id = $socialId;
                $social->data['orderBy'] = $i;
                $social->update($social->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;
        }

        /** получение всех соц. сетей */

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

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

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

        /** вывод в шаблон результатов */
        $this->smarty->assign('totalSocials', $social->total);
        $this->smarty->assign('socials', $socials);
        $this->smarty->assign('pageNums', $pages);


        /** Права доступа к данному шаблону */
        if ($this->permissions('socials')) {
            return $this->smarty->fetch('views/socials/socials.tpl');
        }

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

    }


}



