<?php

namespace App\Http\Controllers\Medium;

use App\DataTables\MediumCategoryDataTable;
use App\DataTables\MediumCategoryDataTableEditor;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class MediumCategoryOverviewController extends Controller
{

    /**
     * MediumCategoryOverviewController constructor.
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * @param MediumCategoryDataTable $dataTable
     * @return mixed
     */
    public function index(MediumCategoryDataTable $dataTable, Request $request)
    {

        if ($request->filtered == 1) {

            $this->handleRequest($request);
        } else {

            if (is_null(session('mediumCategoryLen'))) {
                // set table length
                session(['mediumCategoryLen' => Auth::user()->table_page_length]);
            }
        }

        $page = session('mediumCategoryPage');
        $pageLength = session('mediumCategoryLen');
        $sortc = session('mediumCategorySortColumn');
        $sortd = session('mediumCategorySortDirection');
        $sortcParam = $request->sortc;
        $sortdParam = $request->sortd;

        return $dataTable->with(['page'=>$page, 'pageLength'=>$pageLength, 'sortc'=>$sortc, 'sortd'=>$sortd, 'sortcParam'=>$sortcParam, 'sortdParam'=>$sortdParam])
            ->render('medium.medium-category-overview', ['page'=>$page, 'pageLength'=>$pageLength, 'sortc'=>$sortc, 'sortd'=>$sortd, 'sortcParam'=>$sortcParam, 'sortdParam'=>$sortdParam]);
    }

    /**
     * @param MediumCategoryDataTableEditor $editor
     * @return \Illuminate\Http\JsonResponse|mixed
     * @throws \Yajra\DataTables\DataTablesEditorException
     */
    public function store(MediumCategoryDataTableEditor $editor)
    {
        return $editor->process(request());
    }

    /**
     * @param $request
     */
    public function handleRequest($request) {

        // set page in session
        if (!is_null($request->page)) {
            session(['mediumCategoryPage' => $request->page]);
        } else {
            session(['mediumCategoryPage' => null]);
        }

        // set page length in session
        if ($request->len > 0) {
            session(['mediumCategoryLen' => $request->len]);
        } else {
            session(['mediumCategoryLen' => Auth::user()->table_page_length]);
        }

        // set sort column in session
        if (!is_null($request->sortc)) {
            session(['mediumCategorySortColumn' => $request->sortc]);
        } else {
            session(['mediumCategorySortColumn' => null]);
        }

        // set sort direction in session
        if (!is_null($request->sortd)) {
            session(['mediumCategorySortDirection' => $request->sortd]);
        } else {
            session(['mediumCategorySortDirection' => null]);
        }
    }
}
