<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Http\Requests\API\Plan\CreateOrUpdateRequest;
use App\Http\Resources\API\PlanByAssetResource;
use App\Http\Resources\API\PlanResource;
use App\Http\Resources\API\RequirementSimpleResource;
use App\Models\Asset;
use App\Models\Enums\FileObjectType;
use App\Models\Plan;
use App\Models\Requirement;
use App\Services\File\FileAssociationService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class PlanController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $sort=$request->input('sort','desc');
        $pageSize=$request->get('page_size') ?? 10;
        $plan=Plan::filter($request->all())->allowed()->orderBy('created_at',$sort)->paginate($pageSize);

        $page = $plan->currentPage();

        $newId = ($page - 1) * $pageSize+1;

        $planTree=$plan->each(function ($plan){
            $plan->asset_name= $plan->asset ?  $plan->asset->name : null;
            $plan->requirement_total = $plan->requirements()->count();
            $plan->project_total = $plan->projects()->count();
        });

        $planTree=!empty(make_tree($planTree->toArray()))?make_tree($planTree->toArray()):$planTree->toArray();

        return $this->success([
            'data' => $planTree,
            'total'=>$plan->total()
        ]);

//        $plans = Plan::filter($request->all())->where("parent_id", 0)->orderBy('created_at',$sort)->with(['children','asset'=>function($query){
//            $query->with('parent');
//        }])->paginate($pageSize);
//
//        return PlanResource::collection($plans);

    }


    public function byAssets(Request $request)
    {
        $sort=$request->input('sort','desc');
        $pageSize=$request->get('page_size') ?? 10;
        $assetIds = $request->get("assets", []);
        $emptyResponse = $this->success([
            'data' => [],
            'meta'=>[
                'total'=>0
            ]
        ]);

        if (! $assetIds) {
            return $emptyResponse;
        }

        $assets = Asset::query()->allowed()->where(function ($query) use ($assetIds) {
            foreach ($assetIds as $index => $assetId) {
                $where = $index == 0 ? "where" : "orWhere";
                $query->$where("path", "like", "%,". $assetId . ",%");
            }
        })->pluck("id");

        if ($assets->isEmpty()) {
            return $emptyResponse;
        }

        $plans = Plan::query()->allowed()->with(['asset'])->whereIn("asset_id", $assets->toArray())->orderBy('created_at',$sort)->paginate($pageSize);;

        return PlanByAssetResource::collection($plans);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(FileAssociationService $service, CreateOrUpdateRequest $request)
    {
        $plan = new Plan();

        $plan->mergeFillable([
            'company_id'
        ]);

        $service->check(
            $request->get("file_ids", []),
            FileObjectType::PLAN,
            $request->get("file_uuid"),
        );

        $plan->fill([
            ...$request->all(),
            'company_id' => Auth::user()->company_id,
            'description' => $request->description? (new \App\Services\File\ImageUrlService)->interceptImageUrl($request->description) : null,

        ]);

        $plan->save();

        $service->association($plan->id);

        return $this->created();
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        $plan = Plan::allowed()->findOrFail($id);

        return new PlanResource($plan);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(CreateOrUpdateRequest $request, string $id)
    {
        $plan = Plan::allowed()->findOrFail($id);

        $plan->fill([
            ...$request->all(),
            'description' => $request->description? (new \App\Services\File\ImageUrlService)->interceptImageUrl($request->description) : null,
        ]);

        $plan->save();

        return $this->noContent();
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        $plan = Plan::allowed()->findOrFail($id);
        if(!empty($plan->children()->first())){
            throw new \Exception("Please remove the sub-level plan.");
        }

        $plan->delete();

        return $this->noContent();
    }

    public function notLinkAssetRequirement(string $id){
        $plan=Plan::query()->allowed()->findOrFail($id);

        $requirements=$plan->asset->requirements;

        $filteredRequirements = $requirements->filter(function ($requirement) use ($id) {
            return empty($requirement->plan_id) || $requirement->plan_id != $id;
        });

        return RequirementSimpleResource::collection($filteredRequirements);
    }
}