<?php

namespace App\Http\Controllers\Frontend;

use App\Models\Product;
use App\Models\Project;
use App\Models\ProjectAssociation;
use App\Models\ProjectCategory;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ProjectController 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;
        $projects_count = Project::count();
        if($query) {
            $projects = Project::search($query, null, true)->with('company', 'category')->paginate(36);
        }else{
            $projects = Project::with('company', 'category')->paginate(36);
        }
        return view('frontend.projects.index', compact('projects_count', 'projects', 'query', 'type'));
    }

    public function category(ProjectCategory $category)
    {
        $projects = Porject::with('company', 'category')->where('project_category_id', $category->id)->paginate(36);
        return view('frontend.projects.category', compact('category', 'projects'));
    }

    public function show(ProjectCategory $category, Project $project)
    {
        $projects_associated_ids = ProjectAssociation::where('project_id', $project->id)->where('type', 'project')->distinct()->pluck('associated_id')->all();
        $projects_associated = Project::whereIn('id', $projects_associated_ids)->get();
        $products_associated_ids = ProjectAssociation::where('project_id', $project->id)->where('type', 'product')->distinct()->pluck('associated_id')->all();
        $products_associated = Product::whereIn('id', $products_associated_ids)->get();


        return view('frontend.projects.show', compact('project', 'category', 'projects_associated', 'products_associated'));
    }

    public function position(Project $project)
    {
        return view('frontend.projects.position', compact('project'));
    }
}
