<?php

namespace App\Http\Controllers\Frontend;

use App\Models\Product;
use App\Models\Trend;
use App\Models\TrendAssociation;
use App\Models\TrendCategory;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class TrendController extends Controller
{
    public function index(Request $request)
    {
        $query = !empty($request->get('q')) ? $request->get('q') : null;
        $type = !empty($request->get('type')) ? $request->get('type') : null;
        $trends_count = Trend::count();
        if($query) {
            $trends = Trend::search($query, null, true)->with('company', 'category')->paginate(36);
        }else{
            $trends = Trend::with('company', 'category')->paginate(36);
        }
        return view('frontend.trends.index', compact('trends_count', 'trends', 'query', 'type'));
    }

    public function category(TrendCategory $category)
    {
        $trends = Trend::with('company', 'category')->where('trend_category_id', $category->id)->paginate(36);
        return view('frontend.trends.category', compact('category', 'trends'));
    }

    public function show(TrendCategory $category, Trend $trend)
    {
        $trends_associated_ids = TrendAssociation::where('trend_id', $trend->id)->where('type', 'trend')->distinct()->pluck('associated_id')->all();
        $trends_associated = Trend::whereIn('id', $trends_associated_ids)->get();
        $products_associated_ids = TrendAssociation::where('trend_id', $trend->id)->where('type', 'product')->distinct()->pluck('associated_id')->all();
        $products_associated = Product::whereIn('id', $products_associated_ids)->get();


        return view('frontend.trends.show', compact('trend', 'category', 'trends_associated', 'products_associated'));
    }

    public function position(Trend $trend)
    {
        return view('frontend.trends.position', compact('trend'));
    }
}
