<?php

namespace App\Http\Controllers\Backend;

use App\Group;
use App\Product;
use App\Category;
use Illuminate\Http\Request;
use Auth;
use Image;

class ProductsController extends PostsController
{
    public function index(Request $request)
    {
        $products_total = Product::count();
        $products_active = Product::whereHas('post', function($q) {
            $q->where('active', 1);
        })->count();
        $query = Product::query();
        if($request->has('q')) {
            $query->where('name', 'LIKE', "%{$request->q}%");
        }
        if($request->has('category_id')) {
            $categories = Category::with('products')->whereIn('id', $request->category_id)->get();
            foreach($categories as $category) {
                $query->orWhereIn('id', $category->products->pluck('id')->toArray());
            }
        }
        if($request->has('active')) {
            $query->whereHas('post', function($q) use($request) {
                $q->where('active', $request->active);
            })->count();
        }
        $products = $query->paginate(10);
        $categories = Category::orderBy('order')->get();

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

    public function create(Product $product)
    {
        $categories = Category::orderBy('order')->pluck('title', 'id')->toArray();

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

    public function store(Request $request)
    {
        try {
            $request->validate([
                'post.title' => 'required',
            ], [
                'post.title.required' => 'El producto debe tener título',
            ]);

            $product = Product::create($request->except('_token', '_method', 'image', 'post'));
            $product->post()->create($request->post + ['slug' => slug($request->post['title'])]);

            $this->uploadSingle($request, $product);

            $product->post->categories()->attach($request->category_id);

            return redirect()->route('backend.products.edit', $product)->with('status', 'El producto ha sido creado');
        } catch(\Exception $e) {
            return back()->withInput()->withErrors($e->getMessage());
        }
    }

    public function edit(Product $product)
    {
        $categories = Category::orderBy('order')->pluck('title', 'id')->toArray();

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

    public function update(Product $product, Request $request)
    {
        try {
            $request->validate([
                'post.title' => 'required',
            ], [
                'post.title.required' => 'El producto debe tener título',
            ]);

            $product->fill($request->except('_token') + [
                    'related_id' => $request->related_id ?? null
                ])->save();
            $product->post->fill($request->post + ['image' => null, 'slug' => slug($request->post['title'])])->save();

            $this->uploadSingle($request, $product);
            $this->upload($request->file('images'), $product);

            $product->post->categories()->sync($request->category_id);

            return back()->with('status', 'El producto ha sido actualizado');
        } catch(\Exception $e) {
            return back()->withInput()->withErrors($e->getMessage());
        }
    }

    public function destroy(Product $product)
    {
        try {
            $product->post->categories()->detach();
            $product->post->media()->delete();
            $product->post()->delete();
            $product->delete();

            return back()->with('status', 'El producto ha sido eliminado');
        } catch(\Exception $e) {
            return back()->withInput()->withErrors($e->getMessage());
        }
    }
}
