<?php

namespace App\Http\Controllers\User;

use App\Category;
use App\Product;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\Response
     */

    public function index(Request $request)
    {
        $categoryId = (int) $request->get('category');

        $categories = Category::query()
            ->select('id', 'title')
            ->where('active', 1)
            ->get();

        $products = Product::query()
            ->select([
                'id',
                'title',
                'image',
                'product_price',
                'category_id'
            ])
            ->when($categoryId != null, function ($query) use ($categoryId) {
                return $query->where('category_id', $categoryId);
            })
            ->where([
                ['approved', '=' , 1],
                ['quantity', '>', 0]
            ])
            ->get();

       return view('user.ecommerce.products', [
           'products' => $products,
           'categories' => $categories
       ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\Response
     */
    public function detail($id)
    {
        $productId = (int) $id;

        $product = Product::query()
            ->where([
                ['id', '=', $productId],
                ['approved', '=', 1],
                ['quantity', '>', 0],
            ])
            ->select('id', 'title', 'image', 'description', 'category_id', 'product_price')
            ->with(['category' => function($query) {
                $query->where('active', 1)->select('id', 'title');
            }])
            ->first();

        return view('user.ecommerce.detail', ['product' => $product]);
    }
}
