<?php

namespace App\Http\Controllers\Frontend;

use App\Models\Catalogue;
use App\Models\Category;
use App\Models\Company;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Brand;

class CatalogueController extends Controller
{
    public function index(Request $request, $category = null)
    {
        $query = !empty($request->get('q')) ? $request->get('q') : null;
        $type = !empty($request->get('type')) ? $request->get('type') : null;
        $catalogues_count = Catalogue::count();
        if($query) {
            $catalogues = Catalogue::search($query, null, true)->with('brand', 'category')->orderBy('created_at','desc')->paginate(36);
            return view('frontend.catalogues.search', compact('catalogues_count', 'catalogues', 'query', 'type'));

        }else{
            $last_catalogues = Catalogue::with('category')->orderBy('created_at','desc')->take(12)->get();
            $most_view_catalogues = Catalogue::with('category')->orderBy('number_views','desc')->take(12)->get();
            $categories = Category::where('parent_id', 0)->get();
            //dd($category);
            if(!empty($category)){
                $last_catalogues = Catalogue::with('category')->where('category_id', $category)->orderBy('created_at','desc')->take(12)->get();
                $most_view_catalogues = Catalogue::with('category')->where('category_id', $category)->orderBy('number_views','desc')->take(12)->get();
                return view('frontend.catalogues.category', compact('catalogues_count', 'last_catalogues', 'most_view_catalogues', 'categories'));
            }

            return view('frontend.catalogues.index', compact('catalogues_count', 'last_catalogues', 'most_view_catalogues', 'categories', 'query', 'type'));
        }
    }

    public function show(Brand $brand, Catalogue $catalogue)
    {
        $brand_catalogues = Catalogue::with('brand')->where('brand_id', $brand->id)->where('archive', 0)->get();
        $brand_catalogues_archived = Catalogue::with('brand')->where('brand_id', $brand->id)->where('archive', 1)->get();
        return view('frontend.catalogues.show', compact('brand', 'catalogue', 'brand_catalogues', 'brand_catalogues_archived'));
    }
}
