<?php

namespace Onestartup\Shop\Controller;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Yajra\Datatables\Datatables;
use Onestartup\Shop\Model\ProductShop as Product;
use Onestartup\Shop\Model\ProductCategoryShop as Category;

class ProductController extends Controller
{
    public function index(Request $request)
    {
    	if(isset($request->category)){

            $category = Category::where('slug', $request->category)->first();
            $products = $category->products()->where('active', true)->paginate(config("shop.product-index.pagination"));

        } else {
            $products = Product::where('active', true)->paginate(config("shop.product-index.pagination"));
        }
        $otros = Product::where('active', true)->inRandomOrder()->take(config("shop.product-index.otros"))->get();
        $categories = Category::where('active', true)->get();
        
        return view('shop-public::list')
            ->with('categories', $categories)
            ->with('otros', $otros)
            ->with('products', $products);
        
    }

    public function show($slug)
    {

    	$product = Product::where('slug',$slug)->first();

        $categories = Category::all();

        if ($product != null) {
            if (!$product->active) {
                return redirect('inactivo');
            }
        } else {
            return redirect('no_existe');
        }

        $otros = $product->category->products()->where('active', true)->where('id', '<>', $product->id)->inRandomOrder()->take(config("shop.product-show.otros"))->get(); 

        return view('shop-public::single')
            ->with('product', $product)
            ->with('categories', $categories)
            ->with('otros', $otros);
        
    }

    public function shoByCategory($slug)
    {
        $category = Category::where('active', true)
            ->where('slug', $slug)
            ->first();

        $products = $category->products()->where('active', true)->paginate(config("shop.product-by-category.pagination"));

        $otros = Product::where('active', true)->inRandomOrder()->take(config("shop.product-by-category.otros"))->get();
        $categories = Category::where('active', true)->get();

        return view('shop-public::list')
            ->with('category', $category)
            ->with('categories', $categories)
            ->with('otros', $otros)
            ->with('products', $products);

    }

}