<?php

namespace App\Http\Controllers;

use App\Models\Language;
use App\Models\LevelOfExperience;
use App\Models\Location;
use App\Models\Project;
use App\Models\Rating;
use App\Models\Service;
use App\Models\Skill;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;
use Rinvex\Categories\Models\Category;
use function Symfony\Component\String\s;

class ClientProjectsController extends Controller
{
    public function __construct()
    {
        $this->middleware('project');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $user = Auth::user()->load([
            "projects" => ["files", "location", "skills", "LevelOfExperience"],
            "currency",
        ]);

        $drafts = Project::getAllDrafts()
            ->where("user_id", "=", $user->id);
        foreach ($drafts as $draft){
            $draft->files =[];
            $draft->location=null;
            $draft->skills =[];
            $draft->LevelOfExperience =null;
        }
        $user->projects = collect([$drafts,$user->projects])->flatten();
        return Inertia::render("Projects/Client/Index", [
            "client" => $user,
            "projects" => $user->projects,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $categories = Category::where("parent_id", null)
            ->with("descendants")
            ->get();

        $languages = Language::all();
        $levelsOfExperience = LevelOfExperience::all();
        $budgetTypes = [
            [
                "id" => "Fixed Price",
                "name" => "Fixed Price",
                "value" => "Fixed Price",
                "description" =>
                    "I will pay a fixed price for the whole project",
            ],
            [
                "id" => "Rate",
                "name" => "Rate",
                "value" => "Rate",
                "description" =>
                    "I will pay based on a daily, monthly or yearly rate",
            ],
            [
                "id" => "Bidding",
                "name" => "Bidding",
                "value" => "Bidding",
                "description" =>
                    "I will pay a fixed price that an engineer offers",
            ],
        ];
        $user = Auth::user()->load([
            // "projects" => ["files", "location", "skills", "LevelOfExperience"],
            "currency",
        ]);

        $skills = Skill::where("verified", 1)->get();

        return Inertia::render("Projects/Client/Create/Show", [
            "categories" => $categories,
            "languages" => $languages,
            "levelsOfExperience" => $levelsOfExperience,
            "budgetTypes" => $budgetTypes,
            "client" => $user,
            "skills" => $skills,
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($slug)
    {

        $project= Project::where('slug',$slug)->first()?? Project::getAllDrafts()->where('slug',$slug)->firstOrFail();
//        dd($slug,$project);
        $languages = Language::all();
        $levelsOfExperience = LevelOfExperience::all();

        $project->load(
            [
            "categories",
            "skills",
            "location",
            "invitedEngineers",
            "invitedFirms",
            "files",
            'languageMasteries',
            "proposals" => ["proposalable.user", "files", 'contract'],
            'contract',
            'user.location',
            ]
        );
        $project->files ??=[];
        $project->skills ??=[];
        $invited=[];
        foreach ($project->invitedEngineers as $entity){
            $entity->type='App\Models\Engineer';
            $invited[]=$entity;
        }
        foreach ($project->invitedFirms as $entity){
            $entity->type='App\Models\Firm';
            $invited[]=$entity;
        }
        $project['language'] = $project->languageMasteries[0]['language']??null;


        // dd($project);

        $review = Rating::where('user_id', $project->user_id)->where('rateable_id', $project->id)->where('rateable_type', 'App\Models\Project')->with('user')->first();
        $project['user_rates'] = $review ?  [$review] : null;

        return Inertia::render("Projects/Client/Single/Index", [
            "project" => $project,
            "languages" => $languages,
            "levelsOfExperience" => $levelsOfExperience,
            'invited'=>$invited,
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($slug)
    {
        $project= Project::where('slug',$slug)->first()?? Project::getAllDrafts()->where('slug',$slug)->firstOrFail();
        $categories = Category::where("parent_id", null)
            ->with("descendants")
            ->get();

        $languages = Language::all();
        $levelsOfExperience = LevelOfExperience::all();
        $budgetTypes = [
            [
                "id" => "Fixed Price",
                "name" => "Fixed Price",
                "value" => "Fixed Price",
                "description" =>
                    "I will pay a fixed price for the whole project",
            ],
            [
                "id" => "Rate",
                "name" => "Rate",
                "value" => "Rate",
                "description" =>
                    "I will pay based on a daily, monthly or yearly rate",
            ],
            [
                "id" => "Bidding",
                "name" => "Bidding",
                "value" => "Bidding",
                "description" =>
                    "I will pay a fixed price that an engineer offers",
            ],
        ];

        $user = Auth::user()->load([
            // "projects" => ["files", "location", "skills", "LevelOfExperience"],
            "currency",
        ]);
        if($project->draft==null){
            $project->load(
                "categories",
                "skills",
                "location",
                "files",
                'languageMasteries',
            );
        }else{
            if($project->languageMasteries==null && $project->lang !=null){
                $project->languageMasteries =collect( [
                    Language::find($project->lang),
                ]);
            }
            if($project->specialties_ids!=null){
                $project->categories = [];
                foreach ($project->specialties_ids as $specialty){
                    $project->categories[]= Category::whereId($specialty);
                }
                $project->categories=collect($project->categories);
                $project->hierarchicalCategories=[
                    "category"=>Category::whereId($project->category_id),
                    "sub_categories"=>collect($project->categories),
                ];
            }
            if($project->skills_ids!=null && $project->skills==null){

                $project->skills = [];
                foreach ($project->skills_ids as $skill){
                    $project->skills[]= Skill::find(intval($skill));
                }
                $project->skills=collect($project->skills);
            }
            if($project->location_array!=null){
                $project->location = new Location($project->location_array);
            }
        }



//        dd($project->hierarchicalCategories);
        return Inertia::render("Projects/Client/Update/Show", [
            "categories" => $categories,
            "languages" => $languages,
            "levelsOfExperience" => $levelsOfExperience,
            "budgetTypes" => $budgetTypes,
            "client" => $user,
            'project' => $project
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
