<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Category;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
use Image;

class CategoriesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $query = Category::query()->withCount('products');
        if($request->has('q')) {
            $query->where('title', 'LIKE', "%{$request->q}%");
        }
        if($request->has('active')) {
            $query->where('active', $request->active);
        }
        $categories = $query->orderBy('order')->paginate(10);

        return view('backend.categories.index', [
            'categories' => $categories,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Category $category)
    {
        $categories = Category::orderBy('title')->pluck('title', 'id')->toArray();

        return view('backend.categories.form', [
            'category' => $category,
            'categories' => $categories
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        try {
            $request->validate([
                'slug' => 'nullable|unique:categories,slug',
            ]);

            $category = Category::create($request->except('_method', '_token', 'image') + [
                    'slug' => $request->slug ?? slug($request->title)
                ]);

            $this->upload($request, $category);

            return redirect()->route('backend.categories.edit', $category->id)->with('status', 'La categoría ha sido creada');
        } catch(\Exception $e) {
            return back()->withInput()->withErrors($e->getMessage());
        }
    }

    public function upload($request, $category)
    {
        if($file = $request->file('image')) {
            $path = $file->hashName();
            $image = Image::make($file)->resize(576, 576, function($constraint) {
                $constraint->aspectRatio();
                $constraint->upsize();
            });

            Storage::put($path, $image->encode());

            $url = Storage::url($path);

            $category->fill([
                'image' => $url,
            ])->save();
        }
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Category  $category
     * @return \Illuminate\Http\Response
     */
    public function edit(Category $category)
    {
        return view('backend.categories.form', [
            'category' => $category,
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Category  $category
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Category $category)
    {
        try {
            $request->validate([
                'slug' => 'nullable|unique:categories,slug,'.$category->id,
            ]);

            $category->fill($request->except('_method', '_token') + [
                    'slug' => $request->slug ?? slug($request->title)
                ])->save();

            if($file = $request->file('image')) {
                $this->upload($request, $category);
            }

            return back()->with('status', 'La categoría ha sido editada');
        } catch(\Exception $e) {
            return back()->withInput()->withErrors($e->getMessage());
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Category  $category
     * @return \Illuminate\Http\Response
     */
    public function destroy(Category $category)
    {
        try {
            $category->delete();

            return redirect()->route('backend.categories.index')->with('status', 'La categoría ha sido eliminada');
        } catch(\Exception $e) {
            return back()->withInput()->withErrors($e->getMessage());
        }
    }

    public function order(Request $request)
    {
        foreach($request->post as $key => $id) {
            Category::where('id', $id)->update([
                'order' => $key
            ]);
        }
    }
}
