<?php

namespace App\Http\Controllers;

use App\Http\ViewHelpers\ViewFeeder;
use App\Permission;
use App\Supplier;
use Carbon\Carbon;
use DB;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Lang;
use Redirect;
use Session;

/**
 * Class SupplierController
 * @package App\Http\Controllers
 */
class SupplierController extends Controller implements ViewFeederAwareController
{
    const COLUMNS = [
        'id',
        'name',
        'created_at',
        'updated_at'
    ];

    /**
     * Create a new controller instance.
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $this->validate($request, [
            'sort' => Rule::in(self::COLUMNS),
            'ordering' => 'in:asc,desc',
            'count' => 'integer|min:5|max:100'
        ]);

        $sort = $request->get('sort', 'name');
        $ordering = $request->get('ordering', 'asc');
        $count = intval($request->get('count', 10));;

        $filter = $request->get('name', null);

        $where = [];
        if ($filter) {
            $where[] = ['name', 'LIKE', str_replace('*', '%', $filter)];
        }

        $entityClasses = DB::table('suppliers as s')
            ->select([
                's.id as id',
                's.name as name',
                's.created_at as created_at',
                's.updated_at as updated_at'
            ])
            ->where($where)
            ->orderBy($sort, $ordering)
            ->orderBy('id', 'desc')
            ->paginate($count);

        $viewFeeder = new ViewFeeder($this, ViewFeeder::LIST);

        return view('results.list', $viewFeeder
            ->results($entityClasses)
            ->sorting($sort, $ordering)
            ->permissions([
                'canEdit' => Permission::EDIT_SUPPLIER,
                'canDelete' => Permission::DELETE_SUPPLIER
            ])
            ->feed()
        );
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $viewFeeder = new ViewFeeder($this, ViewFeeder::CREATE);

        return view('non-device.create', $viewFeeder->feed());
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'bail|required|unique:suppliers|max:255'
        ]);

        $supplier = new Supplier([
            'name' => $request->name
        ]);
        $supplier->save();

        Session::flash('success', Lang::get('supplier.create_success'));

        return Redirect::route(self::getRouterName() . '.show', $supplier->id);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Supplier $supplier
     * @return \Illuminate\Http\Response
     */
    public function show(Supplier $supplier)
    {
        $viewFeeder = new ViewFeeder($this, ViewFeeder::SHOW);

        $supplier->children_ids = DB::table('suppliers as s')
            ->where('s.id', '=', $supplier->id)
            ->join('entities as d', 's.id', '=', 'd.supplier_id')
            ->join('entity_classes as dc', 'd.entity_class_id', '=', 'dc.id')
            ->select([
                'dc.id as class_id',
                'dc.name as class_name',
                'dc.is_type as is_type',
                DB::raw('COUNT(*) as entities_count')
            ])
            ->groupBy('dc.id')
            ->get();

        return view('non-device.show', $viewFeeder
            ->result($supplier)
            ->permissions([
                'canEdit' => Permission::EDIT_SUPPLIER,
                'canDelete' => Permission::DELETE_SUPPLIER
            ])
            ->size(6)
            ->feed());
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Supplier $supplier
     * @return \Illuminate\Http\Response
     */
    public function edit(Supplier $supplier)
    {
        $viewFeeder = new ViewFeeder($this, ViewFeeder::EDIT);

        return view('non-device.edit', $viewFeeder
            ->result($supplier)
            ->size(6)
            ->feed());
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \App\Supplier $supplier
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, Supplier $supplier)
    {
        if ($supplier->name === $request->get('name')) {
            Session::flash('error', Lang::get('validation.unchanged'));
            return Redirect::back();
        }

        if ($request->has('id')) {
            Session::flash('error', Lang::get('validation.id_change_forbidden'));
            return Redirect::back();
        }

        $this->validate($request, [
            'name' => 'bail|required|unique:suppliers|max:255'
        ]);

        $supplier->name = $request->name;

        $supplier->updated_at = Carbon::now();
        $supplier->save();

        Session::flash('success', Lang::get('manufacturer.update_success'));

        return Redirect::route(self::getRouterName() . '.show', $supplier->id);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param Supplier $supplier
     * @return \Illuminate\Http\RedirectResponse
     * @internal param int $id
     */
    public function destroy(Supplier $supplier)
    {
        $deleted = $supplier->delete();

        if ($deleted)
            Session::flash('success', Lang::trans('supplier.delete_success', ['id' => $supplier->id]));
        else
            Session::flash('error', Lang::trans('supplier.delete_failed', ['id' => $supplier->id]));

        return Redirect::route(self::getRouterName() . '.index');
    }

    /**
     * Gets the name of the router to be used from the view.
     *
     * @return string
     */
    public static function getRouterName(): string
    {
        return 'suppliers';
    }

    /**
     * Returns singular of object controller is working with.
     *
     * @return string
     */
    public function getSingular(): string
    {
        return 'Supplier';
    }

    /**
     * Returns plural of object controller is working with.
     *
     * @return string
     */
    public function getPlural(): string
    {
        return 'Suppliers';
    }

    /**
     * Returns array of columns to be shown when listing objects controller is working with.
     *
     * @return array
     */
    public function getColumns(): array
    {
        return self::COLUMNS;
    }
}
