<?php

namespace App\Http\Controllers\BackEnd;

use App\Repositories\CategoryRepository;
use App\Repositories\TextsRepository;
use App\Repositories\MessagesRepository;
use App\Repositories\ProductsRepository;
use App\Repositories\UsersRepository;

class PriceController extends BackendController
{
    public function __construct(UsersRepository $users, MessagesRepository $messages, ProductsRepository $products, CategoryRepository $category)
    {
        parent::__construct();
        $this->r_users = $users;
        $this->r_messages = $messages;
        $this->r_products = $products;
        $this->r_category = $category;
    }

    public function index()
    {
        if (!session()->has('admin-filter'.'sort')) {
            session()->put('admin-filter'.'sort', 'all');
        }
        $sort = session()->get('admin-filter'.'sort');

        if(isset($_GET['sort'])) {
            session()->put('admin-filter'.'sort', $_GET['sort']);
            $sort = session()->get('admin-filter'.'sort');
        }

        $messages = $this->getMessages();
        $admin = $this->getAdmin();
        $products = $this->getProductsList($sort);
        $productsTop = $this->getProductsListTop();
        $category = $this->getCategory(2);
        if($category != null) {
            foreach ($category as $item) {
                $podcategory[$item->id] = $this->getCategory($item->id);
            }
        } else {
            $podcategory = null;
        }

        $tag = 'products';

        $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.mainPrice')->with('admin', $admin)->with('products', $products)->with('productsTop', $productsTop)->with('category', $category)
            ->with('podcategory', $podcategory)->with('sort', $sort)->render();
        $this->vars = array_add($this->vars, 'main', $main);

        return $this->renderOutput();
    }

    public function store()
    {
        foreach ($_POST['productID'] as $n => $item) {
            $products = $this->getProducts()->find($item);
            $products->status = $_POST['statusID'][$n];
            $products->price = $_POST['price'][$n];
            $products->save();
        }
        session()->flash('flash_message', 'Вы успешно сохранили изменения!');
        return redirect('/admin/price');
    }
}
