<?php

namespace App\Http\Controllers\BackEnd;

use App\Repositories\ArticlesRepository;
use App\Repositories\CategoryRepository;
use App\Repositories\ContentsRepository;
use App\Repositories\MessagesRepository;
use App\Repositories\ProductsRepository;
use App\Repositories\SettingsRepository;
use App\Repositories\TelsRepository;
use App\Repositories\UsersRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use DiDom\Document;

class ArticlesController extends BackendController
{
    public function __construct(UsersRepository $users, MessagesRepository $messages, ArticlesRepository $articles, CategoryRepository $category)
    {
        parent::__construct();

        $this->r_users = $users;
        $this->r_messages = $messages;
        $this->r_articles = $articles;
        $this->r_category = $category;
    }

    public function index()
    {
        $messages = $this->getMessages();
        $admin = $this->getAdmin();
        $articles = $this->getArticlesList();

        $tag = 'articles';

        $header = view('backend.layouts.header')->with('tag', $tag)->with('messages', $messages)->with('admin', $admin)->render();
        $this->vars = array_add($this->vars, 'header', $header);

        $main = view('backend.layouts.mainArticleList')->with('admin', $admin)->with('articles', $articles)->render();
        $this->vars = array_add($this->vars, 'main', $main);

        return $this->renderOutput();
    }

    public function store()
    {
        if ($_POST['status'] === 'del') {
            $articles = $this->getArticles()->find($_POST['articleID']);
            $articles->delete();
            session()->flash('flash_message', 'Вы успешно сохранили изменения!');
            return redirect('/admin/articles');
        } elseif ($_POST['status'] === 'edit') {
            if ($_POST['alias'] == "") {
                $_POST['alias'] = $this->str2url($_POST['title']) . "-" . $_POST['articleID'];
            }

            $document = new Document($_POST['img']);
            $img = $document->find('img')[0]->attr('src');
            $_POST['img'] = $img;

            $article = $this->getArticles()->find($_POST['articleID']);
            $article->categoryID = $_POST['categoryID'];
            $article->alias = $_POST['alias'];
            $article->title = $_POST['title'];
            $article->description = $_POST['description'];
            $article->h1 = $_POST['h1'];
            $article->img = $_POST['img'];
            $article->text1 = $_POST['text1'];
            $article->text2 = $_POST['text2'];
            $article->save();
            session()->flash('flash_message', 'Вы успешно сохранили изменения!');
            return redirect('/admin/articles');
        } elseif ($_POST['status'] === 'create') {
            $document = new Document($_POST['img']);
            $img = $document->find('img')[0]->attr('src');
            $_POST['img'] = $img;
            $article = $this->createArticle($_POST);
            $article2 = $this->getArticles()->find($article->id);
            $alias = "";
            if ($article->alias == "") {
                $alias = $this->str2url($article->title) . "-" . $article->id;
            }
            $article2->alias = $alias;
            $article2->save();
            session()->flash('flash_message', 'Вы успешно сохранили изменения!');
            return redirect('/admin/articles');
        } else {
            session()->flash('flash_message', 'Что-то пошло не так!');
            return redirect('/admin/articles');
        }
    }

    public function show($articleID)
    {
        $article = $this->getArticles()->find($articleID);
        $messages = $this->getMessages();
        $admin = $this->getAdmin();

        $categoryBlog = $this->getCategory(1);
        foreach ($categoryBlog as $item) {
            $podcategoryBlog[$item->id] = $this->getCategory($item->id);
        }

        $tag = 'articles';

        $header = view('backend.layouts.header')->with('tag', $tag)->with('messages', $messages)->with('admin', $admin)->render();
        $this->vars = array_add($this->vars, 'header', $header);

        $main = view('backend.layouts.mainArticleEdit')->with('admin', $admin)->with('categoryBlog', $categoryBlog)
            ->with('podcategoryBlog', $podcategoryBlog)->with('article', $article)->render();
        $this->vars = array_add($this->vars, 'main', $main);

        return $this->renderOutput();
    }

    public function create()
    {
        $messages = $this->getMessages();
        $admin = $this->getAdmin();

        $categoryBlog = $this->getCategory(1);
        foreach ($categoryBlog as $item) {
            $podcategoryBlog[$item->id] = $this->getCategory($item->id);
        }

        $tag = 'articles';

        $header = view('backend.layouts.header')->with('tag', $tag)->with('messages', $messages)->with('admin', $admin)->render();
        $this->vars = array_add($this->vars, 'header', $header);

        $main = view('backend.layouts.mainArticleCreate')->with('admin', $admin)->with('categoryBlog', $categoryBlog)
            ->with('podcategoryBlog', $podcategoryBlog)->render();
        $this->vars = array_add($this->vars, 'main', $main);

        return $this->renderOutput();
    }

    protected function rus2translit($string) {
        $converter = array(
            'а' => 'a',   'б' => 'b',   'в' => 'v',
            'г' => 'g',   'д' => 'd',   'е' => 'e',
            'ё' => 'e',   'ж' => 'zh',  'з' => 'z',
            'и' => 'i',   'й' => 'y',   'к' => 'k',
            'л' => 'l',   'м' => 'm',   'н' => 'n',
            'о' => 'o',   'п' => 'p',   'р' => 'r',
            'с' => 's',   'т' => 't',   'у' => 'u',
            'ф' => 'f',   'х' => 'h',   'ц' => 'c',
            'ч' => 'ch',  'ш' => 'sh',  'щ' => 'sch',
            'ь' => '',  'ы' => 'y',   'ъ' => '',
            'э' => 'e',   'ю' => 'yu',  'я' => 'ya',

            'А' => 'A',   'Б' => 'B',   'В' => 'V',
            'Г' => 'G',   'Д' => 'D',   'Е' => 'E',
            'Ё' => 'E',   'Ж' => 'Zh',  'З' => 'Z',
            'И' => 'I',   'Й' => 'Y',   'К' => 'K',
            'Л' => 'L',   'М' => 'M',   'Н' => 'N',
            'О' => 'O',   'П' => 'P',   'Р' => 'R',
            'С' => 'S',   'Т' => 'T',   'У' => 'U',
            'Ф' => 'F',   'Х' => 'H',   'Ц' => 'C',
            'Ч' => 'Ch',  'Ш' => 'Sh',  'Щ' => 'Sch',
            'Ь' => '',  'Ы' => 'Y',   'Ъ' => '',
            'Э' => 'E',   'Ю' => 'Yu',  'Я' => 'Ya',
        );
        return strtr($string, $converter);
    }
    protected function str2url($str) {
        // переводим в транслит
        $str = $this->rus2translit($str);
        // в нижний регистр
        $str = strtolower($str);
        // заменям все ненужное нам на "-"
        $str = preg_replace('~[^-a-z0-9_]+~u', '-', $str);
        // удаляем начальные и конечные '-'
        $str = trim($str, "-");
        return $str;
    }
}
